如果 laravel 中不存在加入 table 数据,如何设置默认值?

How to set default value if joining table data not exist in laravel?

我有两个 table。 productinventory。我想 LEFT JOIN productinventory。还有一个基于inventory.stock的求和运算。

我的代码如下,

DB::table('product')
    ->leftjoin('inventory','product.id','=','inventory.product_id')
    ->select('product.id as id',
            'product.name as name',
            'product.color as color',
            'product.unit_price as unit_price',
            DB::raw('SUM(inventory.stock)::integer as available_stock'))
     ->groupBy('product.id')
     ->get();

我的问题是有很多产品在库存中没有行 table。在这种情况下,available_stock 给了我 null。而不是 null 我想显示一个默认字符串。像 "not stocked" 或“0”之类的东西。我怎样才能做到这一点?

我正在使用 postgresql。

这样您可以设置可用库存的默认值。

当库存不可用时,这将为零。

DB::table('product')
->leftjoin('inventory','product.id','=','inventory.product_id')
->select('product.id as id',
        'product.name as name',
        'product.color as color',
        'product.unit_price as unit_price',
        DB::raw('(case when inventory.product_id is null then 0 else SUM(inventory.stock)::integer end) as available_stock'))
 ->groupBy('product.id')
 ->get();