我有一个带有一些表单和CRUD操作的Laravel应用程序。在应用程序上我有这样的关系:
品牌列(在Guns表上)引用了品牌表上的ID。
枪模:
public function brand()
{
return $this->belongsTo('Brand', 'brand', 'id');
}
品牌型号:
public function gun()
{
return $this->hasMany('Gun', 'id', 'brand');
}
如果我尝试从控制器加载枪支数据,使用with,就像这样:
$ results = Gun :: with(' brand') - > findOrFail($ id);
但是,每次我想使用表单模型显示枪支数据时,品牌都会显示为ID,而不是品牌名称。
我尝试为此设置一个Accessor,就像这样(Gun模型):
public function getBrandAttribute ($id)
{
$attribute = Brand::find($id);
return ($attribute ? $attribute->value : $id);
}
它可以工作,但是当我返回包含数据库中所有枪支的列表时,需要花费很多时间。
如何从模型中设置一个可以返回品牌名称的访问者,而无需每次都进行查询?
我在访问器上使用了var_dump $,我看到了枪支数据,但是我无法看到品牌表中的数据。
答案 0 :(得分:0)
When you are eager loading, you don't want to call $gun->brand
to get the name of the brand. That's already been setup to return the Brand
model. In order to get the name of a brand of gun, you would do something like this:
$gun->brand->name;
This is assuming you have a name
column in your brands
table.
You could also set it in the accessor by reaching into the relation which has already been setup.
public function getBrandAttribute()
{
return $this->brand->name;
}
Beware though that Laravel already setup this accessor and with this method, you'd be overwriting that. I'd suggest using a different attribute if you can, ex... getBrandNameAttribute()
答案 1 :(得分:0)
无法通过急切的加载直接获取访问器。使用时必须附加对象。
$guns = Gun::with('brand')->findOrFail($id);
foreach($guns as $gun){
$gun->brand->setAppends(['brand']);
//logic
$brand = $gun->brand->brand;
}