如何使用关联数组键访问 Eloquent 关系

How to access an Eloquent relationship using an associative array key

假设我有一个与属性模型具有一对多关系的列表模型:

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.

中内置的东西来做到这一点

有比我上面建议的更好的想法吗?

您可以在 Laravel 集合上使用带闭包的 first() 方法:

$val = Listing::find($id)->attrs->first(function($model) use ($code){
   return $model->code == $code;
})->value;

但是请注意,如果没有模型匹配,first() 将 return null,您将得到一个异常(因为您无法访问非 ->value -对象)

为避免将其包装在 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';