问题
Using Laravel 4 and I have a mutator set up in my User model:
public function getFullnameAttribute($value)
{
return $this->first_name. ' ' .$this->last_name;
}
But I have a relationship set up in my Cars model for a user ID linked to that car:
public function salesManager()
{
return $this->belongsTo('User', 'sales_manager')->select('first_name', 'last_name');
}
I am calling that relationship on my Car table:
$cars = Car::with('marqueBasic', 'modelBasic', 'salesManager')
->get();
Now, how can I do e.g.
$car->salesManager->fullname
Currently doesn't work, which I am assuming because its in another model to the one thats being called?
The error is: "Trying to get property of non-object"
Am I calling the mutator in the wrong place? I have tried putting it into the relationship select fields but also searched for a field name of fullname and errors out.
回答1:
The probable reason is that you are defining a list of fields to be fetched for the relation.
In order to understand why, you need to first understand how Eloquent eagerly loads salesManager relation when you ask it to fetch all Cars with their SalesManager. Eloquent does the following in such situation:
- Load all cars
- Get values of sales_manager columns for all loaded cars
- Load all users that have id within the values from point 2.
- Map loaded user models to cars by matchingg id of fetched user model and car's sales_manager column.
As you can see, step 4 is impossible to do. User's id field is not listed in the list of fields to be fetched for salesManager relation so Eloquent, when eagerly loading salesManager, won't have a way to match fetched users with the cars. You need to add the field you're referencing in your salesManager relation to the list:
public function salesManager()
{
return $this->belongsTo('User', 'sales_manager')->select('first_name', 'last_name', 'id');
}
来源:https://stackoverflow.com/questions/31696669/using-accessor-mutator-with-a-belongsto-relationship