laravel雄辩的模型强制保存? [英] laravel eloquent model casts on save?
问题描述
https://laravel.com/docs/5.4/eloquent-mutators #attribute-casting 例如
protected $casts = [ 'price' => 'integer', ];
现在这将在检索值时强制转换.保存时,实际上我不确定$book->price = "20"
会做什么,例如最有可能节省20.
protected $casts = [ 'price' => 'integer', ];
now this will cast when retrieving the value. When saving, I am actually not sure what $book->price = "20"
will do, e.g. most likely it will save 20.
这是我的猜测,对吗?
That is my guess, is it right?
$book->someboolean
和$casts =[ 'someboolean' -> 'boolean'];
$book->someboolean = 'false'; $book->save();
$book->someboolean = '0'; $book->save();
$book->someboolean = 0; $book->save();
$book->someboolean = null; $book->save();
它将存储什么?
推荐答案
$casts
不适用于保存和更新方法.当您从模型中获取某些属性时,将调用该函数:__get()
,toArray()
或toJson()
.
$casts
does not work on save and update methods. It is call when you get some property from model: __get()
, toArray()
or toJson()
.
对于MySQL::如果尝试保存"20",则数据库可以根据列类型转换值:如果是整数,则将保存20,如果是布尔值,则为true.
For MySQL: if you try save "20", database can convert value depending on the column type: if it is integer - 20 will be saved, if boolean - true.
布尔型,布尔型:这些类型是TINYINT(1)的同义词.零值被认为是错误的.非零值被认为是正确的.
Bool, Boolean: These types are synonyms for TINYINT(1). A value of zero is considered false. Non-zero values are considered true.
这篇关于laravel雄辩的模型强制保存?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!