Laravel Eloquent 关系与不起作用

问题描述

我正在尝试此代码,但在 whith where query 中不起作用 谁能解决这个问题?

Quotation::with(['QuoParts','client'=>function($cq){
            $cq->orWhere('first_name','LIKE','%Muhammad%');
        },'user'])->orWhere(function($q) use ($s){
            $q->orWhere('sku','%'.$s.'%');
            $q->orWhere('issue_date','%'.$s.'%');
            
        })->take($length)->skip($r->start)->get();

解决方法

$posts = App\User::whereHas('posts',function (Builder $query) {
    $query->where('name','like',`foo%');
})->get();
,

您应该使用where(),然后使用orWhere()

Quotation::with([
    'QuoParts','user','client' => function ($cq) {
        $cq->where('first_name','LIKE','%Muhammad%');
    },])->where(function ($q) use ($s) {
    $q->where('sku','%' . $s . '%');
    $q->orWhere('issue_date','%' . $s . '%');

})->take($length)->skip($r->start)->get();
,

经过大量搜索,我通过使用 WhereHas 闭包 function

解决了这个问题
$q = Quotation::with(['QuoParts','client'])->whereHas('client',function ($query) use ($s) {
            $query->where('sku','%' . $s . '%');
            $query->orWhere('first_name','%' . $s . '%');
            $query->orWhere('last_name','%' . $s . '%');
        })->orWhereHas('user',function ($query) use ($s) {
            $query->where('name','%' . $s . '%');
            
        })
            ->orWhere(function ($q) use ($s) {
                $q->orWhere('sku','%' . $s . '%');
                $q->orWhere('issue_date','%' . $s . '%');
            })
            ->take($length)
            ->skip($r->start)
            ->get();```