在多个表中搜索并在所有表中应用条件

时间:2018-10-16 12:09:59

标签: php mysql laravel laravel-query-builder

我有2个表之间的多对多关系,这个关系存储在ptivot表中,表是

  • cpts
  • 提供者
  • provider_cpts

我想在两个字段中使用关键字搜索cpts,并使用一个关键字搜索提供者,条件必须适用于boh表,例如我要搜索

  

心脏手术

在cpts和

  

俄克拉何马州

在提供程序中,所以我想获取包含那些关键字的所有cpt以及与此cpt相关并包含oklahoma关键字的提供程序的数量。 我正在使用laravel 我尝试这样做

Cpt::where('title', 'like','%' .$keyword.'%')
                ->OrWhere('description','like','%'.$keyword.'%')
                ->whereHas('providers',function($query) use($state){
                    if(!is_null($state)){
                        $query->where('providers.state','like','%'.$state.'%')->orderBy('state')->orderBy('city');
                    }
                })
                ->with('providers','providers.oneCptPrice','prices')
                ->orderBy('id','DESC')->paginate(50);

1 个答案:

答案 0 :(得分:0)

  1. 您需要将前两个where子句分组在一起。

  2. 您不仅需要为whereHas()函数设置条件,还需要为with()函数设置条件。

  3. 您不需要order wherehas()函数。因为你没有得到结果。相反,您需要order with()函数,因为在那里可以得到结果。

Cpt::where(function($query) {
    $query->where('title', 'like','%' .$keyword.'%')
          ->OrWhere('description','like','%'.$keyword.'%')
})
->whereHas('providers',function($query) use($state){
    if(!is_null($state)){
        $query->where('providers.state','like','%'.$state.'%');
    }
})
->with([
    'providers' => function ($query) use ($state) {
        if(!is_null($state)){
            $query->where('providers.state','like','%'.$state.'%')
                  ->orderBy('state')->orderBy('city');
                  ->with('oneCptPrice');
        }
    },
    'price'
])
->orderBy('id','DESC')->paginate(50);