Home > Back-end >  laravel 6 - how to sort by column in a foreign table
laravel 6 - how to sort by column in a foreign table

Time:09-17

I'm sorry if this has been answered to death, but for a week I cannot figure out how to get this to work. I'm using Laravel 6, and I have 3 tables

Facts
id
fact

Likes
id
fact_id

Dislikes
id
fact_id

I've created one to many relationships between the Fact model and the Like / Dislike models. I'm having issues trying to query all 3 tables, and sort the results descending by the total amount of rows from the likes table.

This is the query I am using to at least be able to get all the information from each table

$facts = \App\Fact::with(['likes', 'dislikes'])->paginate(25);

But i am completely lost on how to get it to sort in desc order, for the likes table. Any help would be greatly appreciated, and if I have left out information, I will reply right away with it.

Thanks.

CodePudding user response:

Use withCount for that

$facts = Fact::with(['likes', 'dislikes'])
    ->withCount('likes')
    ->orderByDesc('likes_count')
    ->paginate(25);

https://laravel.com/docs/6.x/eloquent-relationships#counting-related-models

  • Related