Laravel ->with() get specific columns

2021/10/18閱讀時間約 1 分鐘
情境: 每個客戶有多筆聯繫紀錄,contact table有customer_id這個foreign key。
Customer Model (Customer.php):
...

public function contacts()
{
  return $this->hasMany(Contact::class, 'customer_id', 'id');
}
...

(new Customer)::with(['contacts' => function ($query) {
$query->select('customer_id', 'contact_result');
}])
這邊需特別注意,customer_id這個foreign key一定要select(不一定要是第一個欄位),否則會不work。

為什麼會看到廣告
20會員
161內容數
留言0
查看全部
發表第一個留言支持創作者!