Laravel ->with() get specific columns

更新 發佈閱讀 2 分鐘

情境: 每個客戶有多筆聯繫紀錄,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

留言
avatar-img
留言分享你的想法!
avatar-img
Vic Lin的沙龍
20會員
161內容數
Vic Lin的沙龍的其他內容
2023/08/13
父元件 傳遞方法使用@ <template>    ...    <Login @modalClose="modalClose"/> ... </template> <script setup>     const _modal = ref();     function m
2023/08/13
父元件 傳遞方法使用@ <template>    ...    <Login @modalClose="modalClose"/> ... </template> <script setup>     const _modal = ref();     function m
2023/03/25
前情提要 由於我的筆電已經用了10年,無法再戰下去了,且有預算考量,加上使用電腦幾乎都是定點,只有偶爾回家的時候會需要攜帶,因此最終選擇了迷你電腦,體積小不占空間,又方便攜帶,剛好符合我的需求。 菜單 由於這台無法裝獨顯,所以CPU的部分選擇 AMD R5 3400G(含Vega 11內
Thumbnail
2023/03/25
前情提要 由於我的筆電已經用了10年,無法再戰下去了,且有預算考量,加上使用電腦幾乎都是定點,只有偶爾回家的時候會需要攜帶,因此最終選擇了迷你電腦,體積小不占空間,又方便攜帶,剛好符合我的需求。 菜單 由於這台無法裝獨顯,所以CPU的部分選擇 AMD R5 3400G(含Vega 11內
Thumbnail
2023/03/10
Nuxt3中可使用useFetch來獲取數據,不須再引用axios,相當方便: 本筆記參考: https://juejin.cn/post/7104071421160063012 https://juejin.cn/post/7086472647575339045
2023/03/10
Nuxt3中可使用useFetch來獲取數據,不須再引用axios,相當方便: 本筆記參考: https://juejin.cn/post/7104071421160063012 https://juejin.cn/post/7086472647575339045
看更多