我有兩張桌子。product和inventory。我想 LEFT JOIN product。inventory還有一個基于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();我的問題是有很多產品在庫存表中沒有行。在那種情況下,available_stock就是給我null。而不是null我想顯示一個默認字符串。像“沒有庫存”或“0”之類的東西。我怎樣才能做到這一點?我正在使用postgresql。
1 回答

開滿天機
TA貢獻1786條經驗 獲得超13個贊
這樣,您可以設置可用庫存的默認值。
當庫存不可用時,這將為零。
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();
- 1 回答
- 0 關注
- 133 瀏覽
添加回答
舉報
0/150
提交
取消