Eloquent - 修改特定模型的标准()响应

时间:2016-11-24 14:09:23

标签: laravel eloquent

每当使用with() Eloquent方法引入关系时,我会在闭包中做一些事情,并且我不得不重复这段代码:

        'earmarks' => function($q) {
            $q
            ->join('locations', 'locations.id', '=', 'earmarks.location')
            ->select('earmarks.*', 'locations.location AS em_location')
            ->orderBy('date', 'asc');
        }

由于我总是希望在该关系上调用with()时执行上述操作,如何将其添加到我的模型中以便自动添加?

1 个答案:

答案 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();
}])