Laravel Eloquent distinct values

为君一笑 提交于 2020-01-16 04:32:09

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!