需要一些帮助将 SQL 查询转换为 Laravel eloquent
Need some help to convert SQL query to 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 eloquent。
我试试这个:
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'] . "%'))");
这可行,但不能使用分页。有人知道吗?
如果你想要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);
}
我有这个 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 eloquent。 我试试这个:
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'] . "%'))");
这可行,但不能使用分页。有人知道吗?
如果你想要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);
}