Di sini anda boleh lihat saya mempunyai dua car_model
medan jadual utama dan nama perhubungan:
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: [] } ... }
Bagaimana saya boleh mendapatkan data perhubungan apabila saya cuba mendapatkan car_model
相關(guān)關(guān)系并同時(shí)擁有 car_model
perhubungan berkaitan dan mempunyai
$products->first()->car_model->title
產(chǎn)品
Model:
public function car_model(): BelongsTo { return $this->belongsTo(CarModel::class); }dan pertanyaan saya:
$this->products = Product::with( [ 'car_model', ] )->get();??
Saya cadangkan anda menamakan semula hubungan itu kepada model_kereta atau sesuatu selain model_kereta:
public function car_models(): BelongsTo { return $this->belongsTo(CarModel::class); }
Dan pertanyaan boleh ditukar kepada ini
$this->products = Product::with( [ 'car_models', ] )->get();
Kemudian kembali
$products->first()->car_models->title
Saya jumpa penyelesaiannya. Lawati object
轉(zhuǎn)換為 array
后,我可以將 car_model
作為 relationship
di:
$i=$products->first()->toArray(); echo $i['car_model']['title'];
atau
echo ($products->first()->toArray())['car_model']['title']