我想在调用with('category')时为我的Model添加where条件.我的关系是这样的:
class Post extends Model
{
public function category()
{
return $this->belongsTo(Category::class);
}
}
Run Code Online (Sandbox Code Playgroud)
现在我使用此代码来显示帖子类别:
Post::where('slug', $slug)->with('category')->get();
Run Code Online (Sandbox Code Playgroud)
我想在with('category')调用时向Post Model添加where条件.我应该只posts.status== published在with('category')被调用时显示.
我认为return $this->belongsTo(Category::class);我应该添加我的where条件,但这不起作用:
return $this->query()->where('posts.status', 'published')->getModel()->belongsTo(User::class)
Run Code Online (Sandbox Code Playgroud)
如果调用('category'),如何为所有帖子查询添加where条件?我知道Laravel查询范围,但我认为我们可以使用更简单的方法.(也许是$this->belongsTo(Category::class))