模型 hasMany 与 where 条件的关系?

model hasMany Relation with where condition?

我可以使用此代码获取每个类别的所有文章:

$category->article

现在我想获取所有具有某种条件的文章(在文章 table 中)

我试试这个

$category->article->wherePublish(1)->
                    whereFeature('top')->latest()->
                    take(9)->get();

但是我得到这个错误:

Method wherePublish does not exist.

$category->article 执行查询,你得到一个集合。集合没有 wherePublish 和类似的魔术方法,这就是您收到错误的原因。

如果要过滤文章,请使用以下语法:

Article::where('category_id', $category->id)
    ->wherePublish(1)
    ->whereFeature('top')
    ->latest()
    ->take(9)
    ->get();

这适用于 hasOnehasMany 关系。对于 belongsToMany 使用 whereHas() 方法而不是 where().

或者,您可以定义一个单独的关系,例如:

public function filteredArticles()
{
    return $this->hasMany(Article::class, 'article_id')
        ->wherePublish(1)
        ->whereFeature('top')
        ->latest()
        ->take(9);
}

并使用它:

$category->filteredArticles