每当使用with()
Eloquent方法引入关系时,我会在闭包中做一些事情,并且我不得不重复这段代码:
'earmarks' => function($q) {
$q
->join('locations', 'locations.id', '=', 'earmarks.location')
->select('earmarks.*', 'locations.location AS em_location')
->orderBy('date', 'asc');
}
由于我总是希望在该关系上调用with()
时执行上述操作,如何将其添加到我的模型中以便自动添加?
答案 0 :(得分:2)
您可以将回调函数解压缩到Query Scope,或者为该查询创建一个全新的关键字。
public function earmarksWithLocations()
{
return $this->earmarks()
->join('locations', 'locations.id', '=', 'earmarks.location')
->select('earmarks.*', 'locations.location AS em_location')
->orderBy('date', 'asc');
}
->with('earmarksWithLocations')
或
public function scopeWithLocations($q)
{
return $q
->join('locations', 'locations.id', '=', 'earmarks.location')
->select('earmarks.*', 'locations.location AS em_location')
->orderBy('date', 'asc');
}
->with(['earmarks' => function ($q) {
$q->withLocations();
}])