Joshua Hansen
Joshua Hansen

Reputation: 405

Trouble order by when using Eloquent in Laravel

I have 2 tables: books, users (Many to many relationship).

User will follow books and save data in pivot table: follows (id, user_id, manga_id).

How can I count total of follows for each book and order by it?

Upvotes: 1

Views: 56

Answers (3)

Jarek Tkaczyk
Jarek Tkaczyk

Reputation: 81177

Joins will be best in terms of performance, so this is what you should do:

Book::join('follows', 'follows.manga_id', '=', 'books.id')
 ->join('users', 'users.id', '=', 'follows.user_id')
 ->selectRaw('books.*, count(users.id) as follows_count')
 ->groupBy('books.id')
 ->orderBy('follows_count')
 ->get();

Upvotes: 1

lukasgeiter
lukasgeiter

Reputation: 152900

Assuming you have set up your models and relations...

$books = Book::with('users')->get()
             ->sortByDesc(function($model){
                 return $model->users->count();
             });

(users here is the name of the relationship, replace it if you have a different name)

Upvotes: 2

Ali insan Soyaslan
Ali insan Soyaslan

Reputation: 846

With following code you can get followers of each book via an array

$books=DB::table('books')->get();
$total_follows=array('');
 foreach($books as $book)
   $total_follows[$book->id]=DB::table('pivot')->where('manga_id',$book->id)->count();

echo $total_follows[$the_book_id_you_need];

Upvotes: 0

Related Questions