我有两张桌子:posts
和post_sns
posts: id, title, content,..
post_sns: id, post_id, sns_type
关系:一个post
可以有很多post_sns
。
现在我想构建一个查询来获取所有包含sns_type in [2,3]
的帖子。不是2或3,而是2和3甚至更多。请帮我!
使用whereHas()
:
Post::whereHas('postSns', function($q) {
$q->where('sns_type', 2);
})->whereHas('postSns', function($q) {
$q->where('sns_type', 3);
})->get();
您还需要定义关系以使其工作:
public function postSns()
{
return $this->hasMany(PostSns::class, 'post_id');
}