2021-10-18|閱讀時間 ‧ 約 2 分鐘

Laravel ->with() get specific columns

情境: 每個客戶有多筆聯繫紀錄,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。
分享至
成為作者繼續創作的動力吧!
小弟是一位軟體工程師,樂於幫助他人,撰寫技術文章除了幫助自己複習以外,也希望可以幫助到他人,若文章內容有誤,還請大大不吝給予指教!
從 Google News 追蹤更多 vocus 的最新精選內容從 Google News 追蹤更多 vocus 的最新精選內容

發表回應

成為會員 後即可發表留言