here as you can see i have two car_model
both of main table field and relation name:
App\Models\Product {#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" => App\Models\Company {#1506 ▶}
"car_model" => App\Models\CarModel {#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 car_model
in relation ship and having both car_model
how can i get relation data? for example:
$products->first()->car_model->title
Product
model:
public function car_model(): BelongsTo
{
return $this->belongsTo(CarModel::class);
}
and my query:
$this->products = Product::with(
[
'car_model',
]
)->get();
CodePudding user response:
I will suggest you to rename relation with car_models or other name except car_model:
public function car_models(): BelongsTo
{
return $this->belongsTo(CarModel::class);
}
and query can be changed to this
$this->products = Product::with(
[
'car_models',
]
)->get();
then return it with
$products->first()->car_models->title
CodePudding user response:
I found the solution. after converting object
into array
i can access to car_model
as a relationship
:
$i=$products->first()->toArray();
echo $i['car_model']['title'];
or
echo ($products->first()->toArray())['car_model']['title']