Laravel Eloquent 关系 findMany 或 find

Laravel Eloquent Relationships findMany or find

如果您有两个模型 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。那么我还能如何处理这个问题呢?

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

你可能想要的是:

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

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

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

这对我有用 他在查询中结合使用了 with 和 whereHas。