Hi guys, I am trying to understand Eloquent to use it as easily as SQL native, but I find it confusing.
This query with SQL RAW works, but how would it be in Eloquent version? It returns a logged user's rating (if any) and the average of other users' ratings.
SELECT books.*,
GROUP_CONCAT(DISTINCT(bu_logged.rating) SEPARATOR ", ") AS logged_rating,
ROUND(AVG(bu_all.rating),2) AS avg_rating
FROM books
LEFT JOIN book_user bu_all ON books.id = bu_all.book_id
LEFT JOIN book_user bu_logged ON books.id = bu_logged.book_id AND bu_logged.user_id = 2 #example id
GROUP BY books.id;
The relationship between books and users is like this:
book.php:
public function users(){
return $this->belongsToMany(User::class, 'book_user')->withPivot('owner','read_status','rating');
}
user.php:
public function books(){
return $this->belongsToMany(Book::class, 'book_user');
}
The pivot table is 'book_user', with the 'rating' extra field.
Could someone please help me?