【发布时间】:2016-10-29 11:02:31
【问题描述】:
我想在调用 with('category') 时向我的模型添加 where 条件。我的关系是这样的:
class Post extends Model
{
public function category()
{
return $this->belongsTo(Category::class);
}
}
现在我使用此代码显示帖子类别:
Post::where('slug', $slug)->with('category')->get();
我想在调用 with('category') 时将 where 条件添加到 Post Model。如果调用了with('category'),我应该只显示posts.status== published。
我认为return $this->belongsTo(Category::class); 是我应该添加我的 where 条件的地方,但这不起作用:
return $this->query()->where('posts.status', 'published')->getModel()->belongsTo(User::class)
如果调用 with('category'),我如何向所有帖子查询添加 where 条件?
我知道 Laravel 查询范围,但我认为我们可以使用一种更简单的方法。 (也许在$this->belongsTo(Category::class))
【问题讨论】:
标签: php mysql laravel laravel-5 eloquent