• 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.

  • 相关阅读:
    GUC-3 模拟CAS算法
    GUC-2 原子性
    GUC-1 volatile
    NIO-5补充
    NIO-4pipe
    NIO-3网络通信(非阻塞)
    NIO-3网络通信
    NIO-1缓冲区(Buffer)
    NIO-2通道(Channel)
    eclipse安装spring boot插件spring tool suite
  • 原文地址:https://www.cnblogs.com/sgm4231/p/10194746.html
Copyright © 2020-2023  润新知