#How to order elements by hasManyThrough parameter? [Eloquent, pgsql]
10 messages · Page 1 of 1 (latest)
https://laravel.com/docs/10.x/eloquent-relationships#constraining-eager-loads
You should able to apply the scope at inline query
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');
}
https://laracasts.com/series/eloquent-performance-patterns/episodes/18
This would be a good starting point
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
☝️ this man is the real magician