【发布时间】:2021-07-09 12:50:15
【问题描述】:
我意识到当我使用这样的对象转换列时,laravel/eloquent 不会保存我的模型:
$original = '{"test": null}';
$new = '{"test": false}';
原因是转换为对象的属性在 HasAttributes.php::R1577 中是这样评估的(以找出记录是否脏):
} elseif ($this->hasCast($key, ['object', 'collection'])) {
return $this->castAttribute($key, $attribute) ==
$this->castAttribute($key, $original);
即它使用 == 来比较两个对象。所以问题可以像这样重现:
$original = '{"test": null}';
$new = '{"test": false}';
$originalObject = json_decode($original, true);
$newObject = json_decode($new, true);
$original == $new; // false
$originalObject == $newObject; // true <-- this is what laravel does and therefore thinks there was no change
$originalObject === $newObject; // false <-- this is what I want (unless there is a reason not to do it)
是否有理由使用 == 而不是 === 进行比较?有没有办法强制它使用严格比较?
【问题讨论】:
标签: php laravel eloquent casting