【发布时间】: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