问题
PROBLEM SOLVED.
I'm trying to get an person's books, but there are more than one book in my book table since there are different editions of a book. When I list all books of a person, I shouldn't list duplicates.
Here's what I've done so far
Person Model
public function books() {
return $this->belongsToMany('\App\Models\Thing', 'bookxauthor', 'person_id', 'thing_id');
}
PersonController.php
$allbooks = Person::find($id)->books;
This is great, it lists all the books of an author, but I don't need duplicates.
The query below works. type_id means it's a book.
$findBooks = Person::with(array('books' => function($query)
{
$query->where('type_id',"=",3)->groupBy('original_name');
}))->find($id);
$allbooks = $findBooks->books;
回答1:
You could use the groupBy function for collections Eg.
$allbooks = Person::find($id)->books->groupBy('name')->get();
回答2:
The query below works.
$findBooks = Person::with(array('books' => function($query)
{
$query->where('type_id',"=",3)->groupBy('original_name');
}))->find($id);
$allbooks = $findBooks->books;
来源:https://stackoverflow.com/questions/32416110/laravel-eloquent-distinct-values