Laravel:使用'With'子句加入排序表

时间:2014-03-23 08:42:13

标签: php laravel laravel-4 eloquent

我使用的是Laravel 4和Eloquent ORM。我目前正在使用以下代码从我的数据库中提取记录:

public function index($type, $id)
{               
    $asset = Asset::where('public_id', '=', $id)
            ->with('attachments')
            ->with('attachments.attachment')
            ->with('tracks')
            ->with('tracks.track')
            ->where('locale', '=', Config::get('app.locale'))
            ->first();

    return View::make('view-asset.index')
            ->with('asset', $asset)
            ->with('type', $type);
}

使用with('tracks')语句加入此查询的表中有一个名为track_order的列 - 我希望能够对该列的查询部分返回的行进行排序,以便存储在数据库中的曲目以正确的顺序返回。

是否可以这样做,如果是这样,我该怎么做?到目前为止,我尝试过这样的事情:

public function index($type, $id)
{               
    $asset = Asset::where('public_id', '=', $id)
            ->with('attachments')
            ->with('attachments.attachment')
            ->with('tracks')
            ->with('tracks.track')
            ->where('locale', '=', Config::get('app.locale'))
            ->orderBy('tracks.track_order', 'ASC')
            ->first();

    return View::make('view-asset.index')
            ->with('asset', $asset)
            ->with('type', $type);
}

哪个不起作用,除了将内容分成多个查询之外,我无法找到一种方法。

1 个答案:

答案 0 :(得分:3)

你当然可以:

with(['tracks' => function($query)
{
    $query->orderBy('track_order', 'asc');
}])

有关详情,请参阅文档中的Eager Loading Contraints

相关问题