Heim > Fragen und Antworten > Hauptteil
Hier sehen Sie, dass ich zwei car_model
Haupttabellenfelder und Beziehungsnamen habe:
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: [] } ... }
Wie erhalte ich die Beziehungsdaten, wenn ich versuche, die car_model
相关关系并同时拥有 car_model
zugehörige Beziehung abzurufen und gleichzeitig
$products->first()->car_model->title
产品
Modell:
public function car_model(): BelongsTo { return $this->belongsTo(CarModel::class); }und meine Frage:
$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']