使用其他查询实现关系.它们不是基本查询的一部分,并且无权修改基本查询,因此您无法在关系方法中执行此操作.
执行此操作的最佳方法是使用查询范围:
类:
class Post extends Model
{
public function scopeWithCategory($query)
{
return $query->with('category')->where('status', 'published');
}
}
查询:
$posts = Post::where('slug', $slug)->withCategory()->get();
编辑
根据你的评论,我想你可能问过错误的问题.您可能希望发布另一个问题,解释您已设置的内容,以及您需要执行的操作,并查看是否有任何建议.
但是,为了回答这个具体问题,我相信您应该能够使用global query scope执行此操作.这与我上面的原始答案中描述的本地范围不同.
在Eloquent查询构建器上调用get()时,将应用全局查询范围.他们可以访问查询构建器对象,并可以看到已请求加载的项目.因此,您应该能够创建一个全局查询范围来检查是否要急切加载类别,如果是,请添加状态约束.
class Post extends Model
{
/**
* The "booting" method of the model.
*
* @return void
*/
protected static function boot()
{
// make sure to call the parent method
parent::boot();
static::addGlobalScope('checkCategory', function(\Illuminate\Database\Eloquent\Builder $builder) {
// get the relationships that are to be eager loaded
$eagers = $builder->getEagerLoads();
// check if the "category" relationship is to be eager loaded.
// if so, add in the "status" constraint.
if (array_key_exists('category', $eagers)) {
$builder->where('status', 'published');
}
});
}
}
上面的代码显示了使用匿名函数添加全局范围.这样做是为了方便和清晰.我建议创建实际的范围类,如上面链接的文档中所述.