在这里,你可以看到我有两个 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
访问:或