Using accessor mutator with a belongsTo relationship

杀马特。学长 韩版系。学妹 提交于 2019-12-10 15:49:47

问题


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:

  1. Load all cars
  2. Get values of sales_manager columns for all loaded cars
  3. Load all users that have id within the values from point 2.
  4. 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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!