当我尝试将具有缺少属性的模型保存到非NULL数据库字段时,我不希望应用程序对此保持安静,我希望它能够静静地尖叫。但对于那些雄辩的空字符串来说,这很好。
为什么MyModel::create([])
成功?
答案 0 :(得分:0)
class BaseModel extends Eloquent {
public static function boot()
{
parent::boot();
static::creating(function($model) {
static::setNullWhenEmpty($model);
return true;
});
}
private static function setNullWhenEmpty($model)
{
foreach ($model->toArray() as $name => $value) {
if (empty($value)) {
$model->{$name} = null;
}
}
}
}
信用: Set fields to null instead of empty value to avoid problems with nullable foreign keys