在 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 = App\User::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.
轉載于:https://www.cnblogs.com/sgm4231/p/10194746.html