【问题标题】:model hasMany Relation with where condition?模型 hasMany 与 where 条件的关系?
【发布时间】:2017-12-09 05:58:10
【问题描述】:
我可以使用此代码获取每个类别的所有文章:
$category->article
现在我想获取所有具有某种条件的文章(在文章表中)
我试试这个
$category->article->wherePublish(1)->
whereFeature('top')->latest()->
take(9)->get();
但我收到此错误:
方法 wherePublish 不存在。
【问题讨论】:
标签:
php
laravel
laravel-query-builder
【解决方案1】:
$category->article 执行查询并获得一个集合。集合没有 wherePublish 和类似的魔术方法,这就是您收到错误的原因。
如果要过滤文章,请使用以下语法:
Article::where('category_id', $category->id)
->wherePublish(1)
->whereFeature('top')
->latest()
->take(9)
->get();
这适用于hasOne 和hasMany 关系。对于belongsToMany 使用whereHas() 方法而不是where()。
或者,您可以定义一个单独的关系,例如:
public function filteredArticles()
{
return $this->hasMany(Article::class, 'article_id')
->wherePublish(1)
->whereFeature('top')
->latest()
->take(9);
}
并使用它:
$category->filteredArticles