fillable 的正确用法
在laravel文档中这么说:
但是在新增前,需要先在模型类里设定好 fillable 或 guarded 属性,因为 Eloquent 默认会防止批量赋值
但是在实际项目中,我表字段很多可能会超过20个,那么如果一个个去写的话,又很麻烦。
那么有没有什么方法 可以"动态" 填充fillable 属性呢?
在Model class 中 找到了 fillable 方法, 于是这么用:
$data = ['a'=>1, 'b'=>2, 'c'=>3];
$user = new User;
$user->fillable(array_keys($data));
$user->save($data);
但是没有生效,那到底 fillable 怎么用呢?
真心求教 ,谢谢~
可以试试用
forceFill
方法更新$user = new User();
$user ->fillable(['name', 'age']);
$user ->fill(['name' => 'Bruce Lee', 'age' => 18]);
$user ->save();
设置 protected $guarded = []; 属性 参数默认全传