保存新库存项时遇Fillable属性错误?迁移与模型配置方案
解决库存系统Item模型批量赋值异常问题
1. 正确创建数据库迁移
首先通过Artisan命令生成迁移文件:
php artisan make:migration create_items_table
打开生成的迁移文件,在up()方法里定义items表的字段,给quantity设置默认值0:
public function up() { Schema::create('items', function (Blueprint $table) { $table->id(); $table->string('name'); $table->text('description')->nullable(); $table->integer('quantity')->default(0); $table->timestamps(); }); }
执行迁移生成数据表:
php artisan migrate
2. 配置Item模型解决批量赋值异常
批量赋值异常是因为框架默认保护模型字段,防止恶意批量赋值,有两种解决方式:
方法一:指定允许批量赋值的字段(推荐)
打开app/Models/Item.php,添加$fillable属性,列出所有允许通过数组批量赋值的字段:
namespace App\Models; use Illuminate\Database\Eloquent\Model; class Item extends Model { protected $fillable = ['name', 'description', 'quantity']; }
方法二:关闭批量赋值保护(仅适用于完全信任的场景)
如果确认所有字段都可以安全批量赋值,可设置$guarded为空数组:
protected $guarded = [];
验证使用
现在就能正常通过数组批量创建Item记录了,示例代码:
Item::create([ 'name' => '测试商品', 'description' => '这是一个测试商品', 'quantity' => 10 ]);
内容的提问来源于stack exchange,提问作者Sasugae
相关产品推荐
相关产品推荐

