eggplantSword's avatar

OrderBy Relationship column

How can I order using a column from a relationship instead of a regular column.

This is my query so far but it doesn't work as expected the items don't actually get reorganized.

 $user_route_check_outs = SalePointCheckOut::with('salePoint.salePoint', 'route', 'salePointRoute')
            ->whereDate('date', $request->date('filters.date') ?? now())
            ->where('user_id', $request->input('filters.user_id'))
            ->whereHas('salePointRoute', function ($query) {
                $query->orderByDesc('priority');
            });

I want the SalePointCheckOuts to get rearranged. How can I do this correctly?

0 likes
5 replies
eggplantSword's avatar

@MichalOravec great article, but I have another question since my relationship itself is more complex than the ones in the article. I used this library to make the relationship https://github.com/topclaudy/compoships

 public function salePointRoute()
    {
        return $this->belongsTo(SalePointRoute::class, ['route_id', 'sale_point_id'], ['route_id', 'sale_point_id']);
    }

In this case would I do two join statements one with route_id and the other with sale_point_id?

eggplantSword's avatar

@MichalOravec last question, this is my query, now it's ordered correctly but I have a lot of duplicates (3 vs 9), I know that can be fixed with a ->get()->unique() after but I wanted to understand why that is happening.

$user_route_check_outs = SalePointCheckOut::select('sale_point_check_outs.*')
            ->with('salePoint.salePoint', 'route', 'salePointRoute')
            ->join('sale_point_route', 'sale_point_route.sale_point_id', '=', 'sale_point_check_outs.sale_point_id')
            ->join('sale_point_route as spr', 'spr.route_id', '=', 'sale_point_check_outs.route_id')
            ->whereDate('date', $request->date('filters.date') ?? now())
            ->where('user_id', $request->input('filters.user_id'))
            ->orderBy('sale_point_route.priority');
MichalOravec's avatar

@msslgomez You joined the same table two times.

$user_route_check_outs = SalePointCheckOut::with('salePoint.salePoint', 'route', 'salePointRoute')
    ->select('sale_point_check_outs.*')
    ->join('sale_point_route', function ($join) {
        $join
            ->on('sale_point_route.sale_point_id', '=', 'sale_point_check_outs.sale_point_id')
            -on('sale_point_route.route_id', '=', 'sale_point_check_outs.route_id');
    })
    ->whereDate('sale_point_check_outs.date', $request->date('filters.date') ?? now())
    ->where('sale_point_check_outs.user_id', $request->input('filters.user_id'))
    ->orderBy('sale_point_route.priority')
    ->get();
1 like

Please or to participate in this conversation.