Add ->select('name') to your relation definition.
public function dispositionType(): BelongsTo
{
return $this->belongsTo(DispositionType::class)->select('name');
}
I have a disposition model that is related to disposition_type. disposition has a disposition_type_id column.
dispositions columns-> id, name, service, ..., disposition_type_id
disposition_types columns -> id, name, active ...
class Disposition extends Model
{
...
public function dispositionType(): BelongsTo
{
return $this->belongsTo(DispositionType::class);
}
...
}
class DispositionType extends Model
{
...
public function dispositions(): HasMany
{
return $this->hasMany(Disposition::class);
}
...
}
when i run this code It works perfect
Disposition::query()->with(
["dispositionType"]
)->first();
this is the answer
...
"actions_id" => 2
"disposition_status_id" => 2
"disposition_type_id" => 4
"active" => 1
"created_at" => "2024-07-27 03:19:28"
"updated_at" => "2024-07-27 03:19:28"
"disposition_type": {
"id": 4
"name": "plan"
"active": 0
"created_at": "2024-07-27T07:19:25.000000Z"
"updated_at": "2024-07-27T07:19:25.000000Z"
}
but when i want only 1 column of dispositionType for example name
Disposition::query()->with(
["dispositionType:name"]
)->first();
this return null
"actions_id" => 2
"disposition_status_id" => 2
"disposition_type_id" => 4
"active" => 1
"created_at" => "2024-07-27 03:19:28"
"updated_at" => "2024-07-27 03:19:28"
"disposition_type": null
So anybody know what's the reason?
Thanks!
you must include the key in the select
Disposition::query()->with(
["dispositionType:id,name"]
)->first();
Please or to participate in this conversation.