需要一些帮助才能将SQL查询转换为Laravel eloquent

时间:2018-01-18 16:06:39

标签: laravel laravel-eloquent

我有这个SQL查询:

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 "%ори%"))

它有效,但我需要转换为Laravel雄辩。 我试试这个:

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'] . "%'))");

这有效,但不能使用分页。有没有人有任何想法?

1 个答案:

答案 0 :(得分:1)

如果您需要Eloquent解决方案,请使用whereHas()方法:

Book::whereHas('authors', function($q) use($search) {
    $q->where('self_name', 'like', '%' . $search . '%')
      ->orWhere('father_name', 'like', '%' . $search . '%')
      ->orWhere('family_name', 'like', '%' . $search . '%')
})->get();

如果您正确定义了关系,这将有效。在Book模型中:

public function authors()
{
    return $this->belongsToMany(Author::class);
}

Author模型中:

public function books()
{
    return $this->belongsToMany(Book::class);
}