zoukankan      html  css  js  c++  java
  • Laravel attribute casting 导致的 Indirect modification of overloaded property

    在 Laravel model 中,设置了某个属性做 array casting.

    protected $casts = [
            'rounds' => 'array',
    ];
    

    但是在 controller 中执行

    array_push($record->rounds, date("Y-m-d H:i:s"));
    

    时,报错

    production.ERROR: Indirect modification of overloaded property

    可见,casting 并不支持一些针对特定类型的操作,例如无法作为指定类型的函数的参数。

    按照官方文档的做法,应该是先赋值给一个中间变量,进行操作,然后再赋值回去。

    $user = AppUser::find(1);
    $options = $user->options;
    $options['key'] = 'value';
    $user->options = $options;
    $user->save();
    

    所以正确的做法应该是

    $tmp = $record->rounds;
    array_push($tmp, date("Y-m-d H:i:s"));
    $record->rounds = $tmp;
    $record->save();
    

    collection casting

    发现还有 collection casting 的支持,于是尝试了一下。

    // casting 类型
    -  'rounds' => 'array'
    +  'rounds' => 'collection'
    
    // collection 的 push 操作
    // 需要注意,push 之后,需要重新赋值回去。
    -  array_push($record->rounds, date("Y-m-d H:i:s"));
    + $record->rounds = $record->rounds->push(date("Y-m-d H:i:s"));
    
    // 初始化
    -  $game_record->rounds = [];
    + $game_record->rounds = collect([]);
    

    casting 支持的类型

    integer, real, float, double, string, boolean, object, array, collection, date, datetime, and timestamp.

  • 相关阅读:
    Codeforces Round #696 (Div. 2) A
    软件体系结构期末复习
    LINUX 下配置 redis
    2020-09-30 刷题记录
    2020-09-29 刷题记录
    Codeforces Round #673 (Div. 2) A
    2020-09-26 刷题记录
    2020-09-25 刷题记录
    C++ 类虚函数实现原理的验证(指向包含类虚函数地址的数组的指针)
    Saleae8 与 SaleaeLogic、PulseView上位机的使用
  • 原文地址:https://www.cnblogs.com/sgm4231/p/10194746.html
Copyright © 2011-2022 走看看