在 with 查詢中只查詢個別欄位

王成濤發表於2018-09-19

最近在專案開發中,呼叫 with 方法預載入資料,預設會把所有欄位都查詢出來,但是我只想查詢個別欄位。
百度了一下,網上列舉了很多方法。試了一下,發現一個問題,如果我 select 的時候沒有 id 的話就會為 null

public function brand()
 {
        return $this->belongsTo(Brand::class, 'brandId')->select('briefCode');
 }

file
如果 select 的時候有 id 的話就沒有問題

public function brand()
 {
        return $this->belongsTo(Brand::class, 'brandId')->select('id', 'briefCode');
 }

file

網上都沒有說一定要傳 id,:joy: :joy: :joy:

另外又發現一個問題:

在為預載入新增約束條件的時候,如果在閉包中指定 select 欄位,最後關聯也會為 null

$parts = ShippingOrderPart::where('id', 602)
            ->with(['shippingOrder' => function ($query) {
                $query->select('id', 'carrier');
            }])
            ->get();

file
執行的 sql 語句如下:

select * from `shipping_order_parts`  where `id` = 602
select `id`, `carrier` from `shipping_order` where `shipping_order`.`id` in ('1544')

當我不指定 select 欄位,結果正常。
file
執行的 sql 語句如下:

select * from `shipping_order_parts` where `id` = '602'
select * from `shipping_order` where `shipping_order`.`id` in ('1544')

為了點個贊,專門註冊的賬號

相關文章