孩子模型的属性全部在阵列的Laravel

问题描述 投票:1回答:1

我有两张桌子:postspost_sns

  • posts: id, title, content,..
  • post_sns: id, post_id, sns_type

关系:一个post可以有很多post_sns

现在我想构建一个查询来获取所有包含sns_type in [2,3]的帖子。不是2或3,而是2和3甚至更多。请帮我!

laravel query-builder laravel-eloquent
1个回答
0
投票

使用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');
}
© www.soinside.com 2019 - 2024. All rights reserved.