在这里,你可以看到我有两个 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();
P粉5556827182023-12-16 08:19:45
我建议您将关系重命名为 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
P粉1455438722023-12-16 00:19:13
我找到了解决方案。将 object
转换为 array
后,我可以将 car_model
作为 relationship
访问:
$i=$products->first()->toArray(); echo $i['car_model']['title'];
或
echo ($products->first()->toArray())['car_model']['title']