在eloquent中的连接表字段上应用订单

问题描述 投票:0回答:3

我有一个查询,它以一对一的关系将一个表与另一个表连接起来。如何按加入关系中的列对结果进行排序

$relation = ModelObject::where('status', '=', 1)
                            ->with('related_table')
                            ->get()

我需要用related_table的列(例如:名称)对其进行排序。如何在雄辩中做到这一点。

php mysql laravel eloquent
3个回答
0
投票

你可以用这个

 $categories = Category::select(DB::raw('categories.*, count(*) as 
`aggregate`'))
->join('pictures', 'categories.id', '=', 'pictures.category_id')
->groupBy('category_id')
->orderBy('aggregate', 'desc');

0
投票

根据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()

-1
投票

你可以使用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();
© www.soinside.com 2019 - 2024. All rights reserved.