情境: 每個客戶有多筆聯繫紀錄,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。
本筆記參考:
1. https://9iphp.com/web/laravel/laravel-eager-loading-with-specific-columns.html
2. https://stackoverflow.com/questions/19852927/get-specific-columns-using-with-function-in-laravel-eloquent/47238258#47238258