【问题标题】:search in multiple tables with and apply conditions in all tables在多个表中搜索并在所有表中应用条件
【发布时间】:2019-03-20 23:15:54
【问题描述】:

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

  • cpts
  • 供应商
  • provider_cpts

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

心脏手术

在cpts和

俄克拉荷马州

在提供者中,所以我想获取包含这些关键字的所有 cpts 以及与此 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);

【问题讨论】:

    标签: php mysql laravel laravel-query-builder


    【解决方案1】:
    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);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-12-03
      • 1970-01-01
      • 2021-08-14
      • 1970-01-01
      • 1970-01-01
      • 2018-11-18
      • 2021-09-14
      • 1970-01-01
      相关资源
      最近更新 更多