Need some help to convert SQL query to Laravel elo

2019-08-03 22:34发布

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条回答
我命由我不由天
2楼-- · 2019-08-03 22:42

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);
}
查看更多
登录 后发表回答