Here you can see I have two car_model
main table fields and relationship names:
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: [] } ... }
When I try to get the car_model
related relationship and have car_model
at the same time, how do I get the relationship data? For example:
$products->first()->car_model->title
Product number:
public function car_model(): BelongsTo { return $this->belongsTo(CarModel::class); }and my query:
$this->products = Product::with( [ 'car_model', ] )->get();
I recommend that you rename the relationship to car_models or something other than car_model:
And the query can be changed to this
Then return
I found the solution. After converting
object
toarray
, I can accesscar_model
asrelationship
:or