结合访问器和变量逻辑向模型添加自定义属性


Combine accessor and mutator logic to add custom attributes to a model

我知道Laravel的访问器和mutator可以在获取或设置模型时调整属性值。然而,这只能用现有的模型属性来完成。我想知道是否有任何方法可以创建一个访问器和mutator的组合,让我为每个模型项设置自定义属性。

然后,当我使用Eloquent: 检索标签时
$tags = Tag::all();
我可以在循环中访问现有的属性:
foreach ($tags as $tag) {
    echo $tag->id.'<br>';
    echo $tag->name.'<br>';
    // and ohers
}

我设置的自定义的,如$tag->customAttr1, $tag->customAttr2

有可能吗?

下面是向模型添加自定义属性的示例。$appends数组将添加这些。当使用eloquent查询表时,…将调用各自的getter来设置值。

在下面的代码片段中'parent_name'和'parent_img_url'是自定义属性,getParentNameAttributegetParentImgUrlAttribute是getter。

可以根据需要修改getter的代码。

class Code extends Eloquent {
    protected $table = 'codes';
    protected $appends = array('parent_name', 'parent_img_url');
    protected $guarded = array();
    public static $rules = array();
    public function components()
    {
        return $this->belongsToMany('Component', 'component_codes', 'component_id', 'code_id');
    }
    public function getParentNameAttribute()
    {
        $parent = Component::find(50);
        return $parent->name_en;
    }
    public function getParentImgUrlAttribute()
    {
        $parent = Component::find(50);
        return $parent->thumb;
    }
}