Laravel会自动将收集作为键/值返回?

时间:2015-04-19 15:46:32

标签: php laravel laravel-5

在我的应用中,我在表格中设置了一对键/值权限对我的用户设置为hasMany

public function permissions()
{
    return $this->hasMany('Permissions');
}

而不是只有一个数组的集合,我希望它作为一个键值数组返回,这样我就可以访问权限,如:

$user->permissions->blah;

我尝试过一些后期处理,但是当我直接修改permissions属性或创建一个新属性perms时,将其视为修改后的属性,这会影响我可能需要做的任何实际保存

有没有办法直接在PermissionUser模型中实现此功能?

3 个答案:

答案 0 :(得分:3)

是正确的。

照亮\数据库\锋\模型

  /**
         * Dynamically retrieve attributes on the model.
         *
         * @param  string  $key
         * @return mixed
         */
        public function __get($key)
        {
            return $this->getAttribute($key);
        }


public function getAttribute($key)
    {
        $inAttributes = array_key_exists($key, $this->attributes);

        // If the key references an attribute, we can just go ahead and return the
        // plain attribute value from the model. This allows every attribute to
        // be dynamically accessed through the _get method without accessors.
        if ($inAttributes || $this->hasGetMutator($key))
        {
            return $this->getAttributeValue($key);
        }

        // If the key already exists in the relationships array, it just means the
        // relationship has already been loaded, so we'll just return it out of
        // here because there is no need to query within the relations twice.
        if (array_key_exists($key, $this->relations))
        {
            return $this->relations[$key];
        }

        // If the "attribute" exists as a method on the model, we will just assume
        // it is a relationship and will load and return results from the query
        // and hydrate the relationship's value on the "relationships" array.
        if (method_exists($this, $key))
        {
            return $this->getRelationshipFromMethod($key);
        }
    }

实际上

$ user->权限等于$ user-> permissions() - > get()

如果你想做后期处理,请创建一个新功能,如:

public function setPasswordAttribute($value)
    {
        $this->attributes['password'] = \Hash::make($value);
    }

OR

public function getPasswordAttribute()
    {
        return $this->attributes['password'] ;
    }

答案 1 :(得分:0)

此功能用于创建雄辩关系。

如果您想获得自定义响应,那么您需要创建一个返回值的新方法,就像您希望看到它们一样。

答案 2 :(得分:0)

属性访问者

我将如何做到这一点。首先在模型上创建一个受保护/私有数据成员来保存键/值对。这将阻止Eloquent尝试将其保存为模型属性。

protected $permValues = [];

接下来创建一个attribute accessor,以便我们可以构建它们的键/值数组(如果它还不存在)。

public getPermissionValuesAttribute()
{
    if (empty($this->permValues))
    {
        $this->permValues = $this->permissions->lists('value', 'key');
    }

    return $this->permValues;
}

这使得事情几乎和你一样。

$model->permissionValues['blah'];

魔术方法

您可以通过创建一个类来保存权限集并定义__set and __get魔术方法,从而更进一步。

protected $permSet;

public getPermissionSetAttribute()
{
    if (empty($this->permSet))
    {
        $this->permSet = new PermissionSet($this->permissions);
    }

    return $this->permSet;
}

我将让你填写PermissionSet类的空白,但最终结果将完全按照你的意愿工作。

$model->permissionSet->blah;