将访问器更改器与belongsTo关系一起使用 [英] Using accessor mutator with a belongsTo relationship

查看:130
本文介绍了将访问器更改器与belongsTo关系一起使用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用Laravel 4,我在用户模型中设置了一个转换器:

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;
}

但是我在汽车模型中建立了与该汽车链接的用户ID的关系:

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');
}

我在Car桌子上称这种关系为

I am calling that relationship on my Car table:

$cars = Car::with('marqueBasic', 'modelBasic', 'salesManager')
    ->get();

现在,我该怎么办

$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.

推荐答案

可能的原因是您正在定义要为该关系获取的字段列表.

The probable reason is that you are defining a list of fields to be fetched for the relation.

为了理解原因,您首先需要了解Eloquent如何在要求其通过SalesManager提取所有汽车时迅速加载 salesManager 关系.在这种情况下,雄辩的人做了以下事情:

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. 加载所有汽车
  2. 获取所有已装载汽车的 sales_manager 列的值
  3. 加载从第2点开始的值内具有ID的所有用户.
  4. 通过将获取的用户模型的id与汽车的sales_manager列进行匹配,将加载的用户模型映射到汽车上.
  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.

如您所见,第4步是不可能的.用户的 id 字段未列在 salesManager 关系的要获取的字段列表中,因此,雄辩的在急切加载 salesManager 时不会一种将获取的用户与汽车匹配的方法.您需要在与列表相关的 salesManager 关系中添加您要引用的字段:

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');
}

这篇关于将访问器更改器与belongsTo关系一起使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆