Reputation: 596
so i just wondered, if something like this is possible, since my code does not work.
protected $appends = ['position_name'];
public function getPositionNameAttribute()
{
return $this->belongsTo('App\EmployeePosition', 'employee_position_id')->name;
}
Can I append the name of Eloquen relationship model?
edit: so far, i am using this:
foreach ($employees as $e) {
$e->position_name = $e->position->name;
}
Upvotes: 1
Views: 20817
Reputation: 319
Creating an accessor that looks up a value in another model and appending this field by using $appends
is bad practice and will lead to n+1 queries whenever you fetch your Employee model. You should avoid doing this and just use $employee->position->name
.
You should also make sure to use Employee::with('position')
when you need to show the position name, so that the position model is fetched in a single query.
If the position name is something that you need in all your Employee
queries, then you can set the Employee to always eager load the position
by defining the following inside your Employee model:
/**
* The relationships that should always be loaded.
*
* @var array
*/
protected $with = ['position'];
Upvotes: 1
Reputation: 11661
Based on your comments i'd suggest to use the laravel default solution for your problems API resrouces
eg
class EmployeeResource extends JsonResource
{
public function toArray($request)
{
return [
'id' => $this->id,
'name' => $this->name,
'email' => $this->email,
'position_name' => $this->position->name,
];
}
}
note: using the with
as other people suggested to preload information can increase performance by reducing the amount of queries, if you are returning a collection of employees.
Upvotes: 0
Reputation: 596
So, I needed to use the relation defined before.
protected $appends = ['position_name'];
public function position()
{
return $this->belongsTo('App\EmployeePosition', 'employee_position_id');
}
public function getPositionNameAttribute()
{
return $this->position->name;
}
Upvotes: 2
Reputation: 1
I think you can just create a model with position names and reference it to the position id in the other mode by using eloquent relationships.
Upvotes: -1