【问题标题】:Laravel Eloquent Relationships findMany or findLaravel Eloquent 关系 findMany 或 find
【发布时间】:2017-03-07 05:49:19
【问题描述】:

如果你有两个模型Post和Comment,并且在Comment模型中你定义了一个belongsTo(),关系叫做posts,我知道可以这样做:

App\Comment::find(1)->posts()->where('category', 3)->get()

但我想要的是将多个主键 id 传递给 find 方法,例如:

App\Comment::find([1,2,3])->posts()->where('category', 3)->get()

或者

App\Comment::findMany([1,2,3])->posts()->where('category', 3)->get()

这两个给了我错误method posts does not exist。那么我还能如何处理这个问题呢?

【问题讨论】:

  • 我终于从@Lukasgeiter找到了最好的方法,他在查询中使用了with和whereHas的组合。
  • 我使用的查询比我的示例更复杂,您的答案在单独使用时对我不起作用,因此我决定结合使用 with 和 whereHas。不过,您的回答对我有所帮助。

标签: php laravel laravel-5 eloquent relationship


【解决方案1】:

当您使用find() 方法时,您会得到一个模型,但findMany() 返回一个集合。

你可能想要的是这个:

App\Comment::whereIn('id', [1, 2, 3])->with(['posts' => function($q) {
    $q->where('category', 3);
}])->get();

【讨论】:

  • 非常感谢,最好使用$q->where('posts.category', 3);,因为两个表可以有相同的列
【解决方案2】:

这对我有用@Lukasgeiter 他在查询中使用了 with 和 whereHas 的组合。

【讨论】:

    【解决方案3】:

    为此,您必须使用回调方法,如下所示

    App\Comment::whereIn('id', [1, 2, 3])->with(['posts' => function($query) {
         $query->whereCategory(3);
    }])->get();
    

    【讨论】:

    • 你不应该复制粘贴别人的答案。您复制了 $q 而不是 $query (在原始文档中到处都是),并且您从原始答案 })->get() 而不是 }])->get() 复制了我的错误,我在发布原始答案后一分钟内修复了该错误.
    • @AlexeyMezenin 有点可疑。
    猜你喜欢
    • 1970-01-01
    • 2016-08-13
    • 2018-02-09
    • 2020-10-14
    • 1970-01-01
    • 1970-01-01
    • 2013-05-27
    • 2016-11-21
    • 2015-01-01
    相关资源
    最近更新 更多