我有一个查询,它以一对一的关系将一个表与另一个表连接起来。如何按加入关系中的列对结果进行排序
$relation = ModelObject::where('status', '=', 1)
->with('related_table')
->get()
我需要用related_table
的列(例如:名称)对其进行排序。如何在雄辩中做到这一点。
你可以用这个
$categories = Category::select(DB::raw('categories.*, count(*) as
`aggregate`'))
->join('pictures', 'categories.id', '=', 'pictures.category_id')
->groupBy('category_id')
->orderBy('aggregate', 'desc');
根据laravel docs,你可以添加这样的附加约束,
限制急切负荷
有时您可能希望加载关系,但也为热切加载查询指定其他查询约束。这是一个例子:
$users = App\User::with(['posts' => function ($query) {
$query->where('title', 'like', '%first%');
}])->get();
最后你的代码应该是这样的,
$relation = ModelObject::where('status', '=', 1)
->with(['related_table' => function($query) {
$query->orderBy('field', 'asc|desc');
}])
->get()
你可以使用orderBy
$relation = ModelObject::where('status', '=', 1)
->with('related_table')
->orderBy('related_table.field') //field name is the name of the field on the basis of which you want to sort
->get();