在這裡,你可以看到我有兩個 car_model
主表欄位和關係名稱:
AppModelsProduct {#1478 ▼ #connection: "mysql" #table: "products" ... #escapeWhenCastingToString: false #attributes: array:21 [▼ "id" => 1 "company_id" => 1 ... "car_model" => "test" ... ] #original: array:21 [▶] ... #relations: array:5 [▼ "company" => AppModelsCompany {#1506 ▶} "car_model" => AppModelsCarModel {#1508 ▼ #connection: "mysql" #table: "car_models" #attributes: array:6 [▼ "id" => 1 "title" => "test" "created_at" => ":07:25" "updated_at" => ":07:58" ] ... +mediaConversions: [] +mediaCollections: [] #deletePreservingMedia: false #unAttachedMediaLibraryItems: [] } ... }
當我嘗試取得 car_model
相關關係並同時擁有 car_model
時,我該如何取得關聯式資料?例如:
$products->first()->car_model->title
產品
型號:
public function car_model(): BelongsTo { return $this->belongsTo(CarModel::class); }
和我的查詢:
$this->products = Product::with( [ 'car_model', ] )->get();
我建議您將關係重新命名為 car_models 或 car_model 之外的其他名稱:
並且查詢可以更改為這樣
然後回傳
我找到了解決方案。將
object
轉換為array
後,我可以將car_model
作為relationship
存取:或