需要一些帮助将SQL查询转换为雄辩的Laravel [英] Need some help to convert SQL query to Laravel eloquent

查看:51
本文介绍了需要一些帮助将SQL查询转换为雄辩的Laravel的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个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. 我尝试这个:

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?

推荐答案

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

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();

如果正确定义关系,此方法将起作用.在Book模型中:

This will work if you properly defined relationships. In the Book model:

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

Author模型中:

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

这篇关于需要一些帮助将SQL查询转换为雄辩的Laravel的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆