Hi all !
I have a table users, a table books and a table book_user between for many_to_many relationship :
users :
- id : int
- name : varchar
boooks :
- id : int
- name : varchar
- color : varchar
book_user :
- book_id : int
- user_id : int
I declared the relation in both Models
// in User.php :
public function books()
{
return $this->belongsToMany(Book::class);
}
// in Book.php
public function users()
{
return $this->belongsToMany(User::class);
}
I want to get all the distinct color of the books of a user (to make a list for a select in a filter area). If I make this call with eloquent :
return $myuser->books()->select('color')->distinct()->get();
I get duplicate colors because eloquent add the pivot table attribute in the select. Here is what I get in SQL :
SELECT DISTINCT
`color`,
`book_user`.`user_id` AS `pivot_user_id`,
`book_user`.`book_id` AS `pivot_book_id`
FROM
`books`
INNER JOIN `book_user` ON `books`.`id` = `book_user`.`book_id`
WHERE
`book_user`.`user_id` = ?
Do you know what I could do to get only the color in the select to perform a real distinct ? The SQL result should be
SELECT DISTINCT
`color`
FROM
`books`
INNER JOIN `book_user` ON `books`.`id` = `book_user`.`book_id`
WHERE
`book_user`.`user_id` = ?