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

Laravel nesting where clause (Query Builder)

所以我对 laravel 嵌套查询感到困惑。 我正在尝试准备一个搜索功能来过滤 sales_agreement table 中的产品,但如果记录有融资,我也希望它也被过滤。
下面是我的示例。

(1) Table 产品

        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_agreement table 中的所有产品。但我也想考虑在 sales_agreement table 中有融资记录的项目。在这一点上,我不知道该怎么做。

任何 comments/suggestion/answer 将不胜感激。谢谢!

你可以试试where 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();

如果你想排除没有融资记录的产品,你可以做一个带有附加子句的左连接

$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();