在这里你可以看到我有两个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
Product
模型:
public function car_model(): BelongsTo
{
return $this->belongsTo(CarModel::class);
}
和my query:
$this->products = Product::with(
[
'car_model',
]
)->get();
我建议您将关系重命名为car_models或car_model以外的其他名称:
public function car_models(): BelongsTo
{
return $this->belongsTo(CarModel::class);
}
和query可以更改为
$this->products = Product::with(
[
'car_models',
]
)->get();
然后返回
$products->first()->car_models->title
我找到了解决方案。在将object
转换为array
后,我可以访问car_model
作为relationship
:
$i=$products->first()->toArray();
echo $i['car_model']['title'];
或
echo ($products->first()->toArray())['car_model']['title']