【问题标题】:Searching from model and related model in laravel5在 laravel5 中从模型和相关模型中搜索
【发布时间】:2015-05-09 18:49:11
【问题描述】:

我想在 Laravel5 中使用 Elequent 从一个表及其所有相关表中进行关键字搜索。 我的控制器是

 $clients = Client::with('contacts', 'paymentTerm', 'addressInfo');
    if ($q = Request::input("q")) {
        $clients->where("clients.name", 'LIKE', "%$q%");
        $clients->where("address_info.email", 'LIKE', "%$q%");//This is not working,I want to search from both client and client address_info
    }
    return $clients->paginate(10);

客户端模型,

 public function addressInfo() {
    return $this->hasOne('App\Model\ClientAddressInfo');
}

客户地址信息,

public function client() {
        return $this->belongsTo('App\Model\Client');
    }

如何在这里应用关键字搜索?

【问题讨论】:

    标签: php mysql laravel laravel-5


    【解决方案1】:

    您可以使用whereHas按相关模型进行过滤:

    $clients->whereHas('addressInfo', function($query) use ($q){
        $query->where("email", 'LIKE', "%$q%");
    });
    

    【讨论】:

    • 谢谢你的回答,它正在工作,但问题是这里有两个条件加入“and”,它是如何产生“or”的?
    • 只需使用orWhereHas 而不是whereHas(它与两个“正常”wheres 的工作方式相同)
    • 我如何从相关模型$clients->orderBy('addressInfo.email');中排序?
    • 不幸的是,如果您使用联接,这是可能的。 See this
    • 所以我需要将 Elequent 方法更改为 db 方法?
    猜你喜欢
    • 2021-02-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-03-13
    • 2014-07-02
    • 1970-01-01
    • 2021-09-19
    相关资源
    最近更新 更多