【问题标题】:Laravel where attribute of child model all in arrayLaravel 子模型的属性都在数组中
【发布时间】:2018-06-04 23:16:45
【问题描述】:

我有 2 张桌子: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】:

使用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');
}

【讨论】:

  • 我尝试了你的方法,但它返回 null :( 我打印这个查询然后它显示:“select * from posts where exists (select * from post_sns where posts.id = post_sns.post_id and sns_type = 2和 sns_type = 3"。你能帮我吗?也许它与 2 和 3 比较一次只有一个 sns_type?
  • @NganNguyen 查询看起来不错。代码无法返回null。它应该返回一个帖子集合或只是一个空集合。请显示您正在使用的确切代码并告诉我确切返回的代码null
  • 对不起,它返回空集合。 $posts = Post::whereHas('postSns', function ($query) { $query->where('social_media_type', 3) ->where('social_media_type', 5); }) ->get();在数据库中我有: post: id =1 / post_sns: post_id =1 , sns_type=2 post_id = 1, sns_type =3 它应该返回帖子有 id =1
  • @NganNguyen 很高兴它有帮助。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-01-15
  • 1970-01-01
  • 2014-06-17
  • 1970-01-01
  • 1970-01-01
  • 2017-06-27
  • 2019-03-04
相关资源
最近更新 更多