假设我有一个与属性模型具有一对多关系的列表模型:
class Listing extends Eloquent {
public function attrs() {
return $this->hasMany('Attribute');
}
}
class Attribute extends Eloquent {
public function listing() {
return $this->belongsTo('Listing');
}
}
属性有代码和值。当我处理清单时,我希望能够使用属性代码获取特定属性,如下所示:
$val = Listing::find($id)->attrs[$code]->value;
上述界限显然无效。有很多方法可以解决这个问题(例如,维护一个由代码索引的内部关联属性数组,并在attrs()方法中填充它;提供一个getter函数,只需通过attrs数组进行强力搜索)但我想知道是否使用Laravel内置的东西,有一种优雅的方式。
任何想法都比我上面建议的好吗?
答案 0 :(得分:1)
您可以在Laravel集合上使用first()
方法和闭包:
$val = Listing::find($id)->attrs->first(function($model) use ($code){
return $model->code == $code;
})->value;
但请注意,如果没有模型匹配,first()
将返回null
,您将获得异常(因为您无法访问非对象的->value
)< / p>
要避免将其包装在if:
中$attribute = Listing::find($id)->attrs->first(function($model) use ($code){
return $model->code == $code;
});
$val = $attribute ? $attribute->value : 'default';
或者你可以过滤关系,我认为这种关系更优雅:
$attribute = Listing::find($id)->attrs()->where('code', $code)->first();
$val = $attribute ? $attribute->value : 'default';