代码之家  ›  专栏  ›  技术社区  ›  jerome

Laravel嵌套where子句(查询生成器)

  •  0
  • jerome  · 技术社区  · 6 年前

    所以我对laravel嵌套查询感到困惑。 我正在尝试准备一个搜索功能,用于过滤 sales_agreement 表,但如果记录有资金,我也希望它被过滤。
    下面是我的样本。

    (1) 表产品

            id         product_name         price
             1           car                 500k
             2           jeep                200k
             3           motor               100k
             4           bicycle             5k
    


    (2) 销售协议书

            id         product_id         price        financing
             1           2                 500k           BPI
             2           1                 200k           MetroBank
             3           3                 100k 
    

    我的查询中的预期输出

           product_id            product_name
              2                      jeep
              1                       car
              4                      bicycle
    

    我的查询

      $result = DB::table('products')
            ->whereNotIn('id',function($q){
                $q->select('product_id')->from('sales_agreement');
            })->where('product_name','LIKE','%' . $get['q'] . '%')
            ->select('id','product_name')
            ->get();
    

    这将过滤sales\u agreement表中未包含的所有产品。但我还想考虑sales\u协议表中有融资记录的项目。在这一点上,我不知道怎么做。

    如有任何意见/建议/答复,将不胜感激。谢谢

    2 回复  |  直到 6 年前
        1
  •  1
  •   athulpraj    6 年前

    可以在null处尝试

        $result = DB::table('products')
        ->whereNotIn('id',function($q){
            $q->select('product_id')->from('sales_agreement')
              ->whereNull('financing');
        })->where('product_name','LIKE','%' . $get['q'] . '%')
        ->select('id','product_name')
        ->get();
    
        2
  •  0
  •   M Khalid Junaid    6 年前

    如果要排除没有融资记录的产品,可以使用附加子句进行左连接

    $result = DB::table('products as p')
                ->leftJoin('sales_agreement as s', function ($query) {
                    $query->on('p.id', '=', 's.product_id')
                          ->whereNull('s.financing');
                })
                ->whereNull('s.product_id')
                ->where('p.product_name', 'LIKE', '%' . $get['q'] . '%')
                ->select('p.id', 'p.product_name')
                ->get();