在這裡,你可以看到我有兩個(gè) car_model
主表欄位和關(guān)係名稱:
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: [] } ... }
當(dāng)我嘗試取得 car_model
相關(guān)關(guān)係並同時(shí)擁有 car_model
時(shí),我該如何取得關(guān)聯(lián)式資料?例如:
$products->first()->car_model->title
產(chǎn)品
型號(hào):
public function car_model(): BelongsTo { return $this->belongsTo(CarModel::class); }
和我的查詢:
$this->products = Product::with( [ 'car_model', ] )->get();
我建議您將關(guān)係重新命名為 car_models 或 car_model 之外的其他名稱:
public function car_models(): BelongsTo { return $this->belongsTo(CarModel::class); }
並且查詢可以更改為這樣
$this->products = Product::with( [ 'car_models', ] )->get();
然後回傳
$products->first()->car_models->title
我找到了解決方案。將 object
轉(zhuǎn)換為 array
後,我可以將 car_model
作為 relationship
存?。?/p>
$i=$products->first()->toArray(); echo $i['car_model']['title'];
或
echo ($products->first()->toArray())['car_model']['title']