Need some help to convert SQL query to Laravel eloquent

大兔子大兔子 提交于 2019-12-24 12:12:03

问题


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

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