问题
I have this SQL query:
SELECT * FROM books WHERE id IN
(SELECT book_id FROM `author_book` WHERE author_book.author_id IN
(SELECT id FROM authors WHERE self_name like "%ори%" OR father_name LIKE "%ори%" OR family_name LIKE "%ори%"))
It works, but I need convert to Laravel eloquent. I try this:
DB::select("SELECT * FROM books WHERE id IN "
. "(SELECT book_id FROM `author_book` WHERE author_book.author_id IN "
. "(SELECT id FROM authors WHERE self_name like '%" . $attributes['search'] . "%' "
. "OR father_name LIKE '%" . $attributes['search'] . "%' "
. "OR family_name LIKE '%" . $attributes['search'] . "%'))");
And this works, but can't use pagination. Does anyone have any idea?
回答1:
If you want Eloquent solution, use the whereHas() method:
Book::whereHas('authors', function($q) use($search) {
$q->where('self_name', 'like', '%' . $search . '%')
->orWhere('father_name', 'like', '%' . $search . '%')
->orWhere('family_name', 'like', '%' . $search . '%')
})->get();
This will work if you properly defined relationships. In the Book
model:
public function authors()
{
return $this->belongsToMany(Author::class);
}
And in the Author
model:
public function books()
{
return $this->belongsToMany(Book::class);
}
来源:https://stackoverflow.com/questions/48325545/need-some-help-to-convert-sql-query-to-laravel-eloquent