#How to order elements by hasManyThrough parameter? [Eloquent, pgsql]

10 messages · Page 1 of 1 (latest)

jade cave
#

How to order elements by hasManyThrough parameter? [Eloquent, pgsql]

prime cipher
#

If the relationship by default is ordering by the column, you could just add it to the relationship

public function visits()
    {
        return $this->hasManyThrough(CardUse::class, Card::class, 'room_id', 'card_id', 'id', 'id')->orderByDesc('created_at');
    }
flint totem
prime cipher
#

I thinks it is not archiable with has many through relationship, you will need to combine the join query and sub query

#

https://laravel.com/docs/10.x/eloquent#subquery-ordering

Example Query:

WareHouse::query()->orderByDesc(
        Card::query()->selectRaw('max(card_uses.created_at)')
        ->join('card_uses', 'cards.id', '=', 'card_uses.card_id')
        ->whereColumn('ware_houses.id', 'cards.room_id')
        ->take(1)
)->get();
#

o missed that, should be card_uses.created_at

#

probably due to ambigious column, need to specify the table for the same name column