dsbx40787736 2016-11-12 21:39
浏览 19

同时使用Laravel演员和变异器

This is part of my Role model:

namespace App;

use App\Traits\Permissions;
use Illuminate\Database\Eloquent\Model;

class Role extends Model
{
    use Permissions;

    /**
     * {@inheritDoc}
     */
    protected $casts = [
        'permissions' => 'array',
    ];
}

This is my Permissions trait:

namespace App\Traits;

trait Permissions
{
    public function setPermissionsAttribute($permissions)
    {
        ksort($permissions);

        $this->attributes['permissions'] = $permissions;
    }
    /**
     * Adds a permission.
     *
     * @param  string $permission
     * @param  bool $value
     * @return void
     */
    public function addPermission($permission, $value = true)
    {
        if (!array_key_exists($permission, $this->getAttribute('permissions'))) {
            $this->setAttribute('permissions', array_merge($this->getAttribute('permissions'), [$permission => $value]));
        }
    }
}

This will throw the following exception:

QueryException in Connection.php line 769:
Array to string conversion (SQL: update `roles` set `permissions` = 1 where `id` = 46526e77-98b8-4126-aaae-7e109c7ea227)

If I print the $permissions variable after the ksort operation it correctly has the permissions array:

array:1 [
  "do.this" => true
]

If I remove the setPermissionsAttribute function it properly serializes the array into json and stores it in the database.

Am I doing something wrong or it's just not possible to use both these features?

  • 写回答

2条回答 默认 最新

  • doubihuai8468 2018-06-25 06:46
    关注

    $cast is also sort of a mutator itself. It doesnt make sense to have both any way. You should define another field that is based on the permissions attribute.

    评论

报告相同问题?

悬赏问题

  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测
  • ¥15 ETLCloud 处理json多层级问题
  • ¥15 matlab中使用gurobi时报错
  • ¥15 这个主板怎么能扩出一两个sata口
  • ¥15 不是,这到底错哪儿了😭
  • ¥15 2020长安杯与连接网探
  • ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么