简体   繁体   English

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

[英]search in multiple tables with and apply conditions in all tables

i have 2 tables relation many to many between them, this relation stored in a ptivot table tables are 我有2个表之间有很多关系,这个关系存储在ptivot表中。

  • cpts CPTS
  • providers 供应商
  • provider_cpts provider_cpts

i want to search in cpts with keyword in two fields and search in providers with one keyword the conditions must apply on boh tables for example i want to search for 我想在两个字段中用关键字搜索cpts,并用一个关键字搜索提供者,条件必须适用于boh表,例如我要搜索

heart surgery 心脏手术

in cpts and 在cpts和

oklahoma 俄克拉何马州

in providers so i want to get all cpts that contain those keyword and the count of provider that related to this cpt and contain oklahoma keyword. 在提供程序中,因此我想获取所有包含那些关键字的cpts以及与此cpt相关并包含oklahoma关键字的提供程序的计数。 im using laravel i tried doing this 我正在使用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. you need to group first two where clauses together. 您需要将前两个where子句组合在一起。

  2. you need to set the conditions not only to the whereHas() function, but to the with() function too. 你需要设定的条件不仅对whereHas()函数,但对with()函数了。

  3. And you don't need to order the wherehas() function. 而且您不需要order wherehas()函数。 Because you don't get the results. 因为你没有得到结果。 Instead you need to order the with() function, Because you get the results there. 相反,您需要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);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM