Laravel 11向shopping_lists表插入数据时触发外键约束违反错误
问题根源及解决方案
1. 用户ID字段类型不匹配(核心问题)
你的users表中user_id是字符串类型($table->string('user_id')->primary()),但shopping_lists表中user_id被定义为整数类型($table->integer('user_id')->notNullable())。SQLite对外键约束的类型匹配要求非常严格,即使值存在,类型不一致也会触发外键约束失败。
修复步骤:
创建新的迁移文件修改shopping_lists的user_id类型:
<?php use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; use Illuminate\Support\Facades\Schema; class FixShoppingListsUserIdType extends Migration { public function up(): void { Schema::table('shopping_lists', function (Blueprint $table) { // 先移除旧外键 $table->dropForeign(['user_id']); // 修改字段类型为string $table->string('user_id')->notNullable()->change(); // 重新添加外键 $table->foreign('user_id')->references('user_id')->on('users'); }); } public function down(): void { Schema::table('shopping_lists', function (Blueprint $table) { $table->dropForeign(['user_id']); $table->integer('user_id')->notNullable()->change(); $table->foreign('user_id')->references('user_id')->on('users'); }); } }
执行迁移:
php artisan migrate
2. 路由ID查询条件错误
在控制器的store方法中,检查route_id是否存在时,使用了错误的字段名:
$route = DB::table('routes')->where('id', $validatedData['route_id'])->first();
你的routes表主键是route_id,不是id,修正为:
$route = DB::table('routes')->where('route_id', $validatedData['route_id'])->first();
3. 确认模型可填充字段
确保App\Models\ShoppingList模型中包含正确的$fillable属性:
<?php namespace App\Models; use Illuminate\Database\Eloquent\Model; class ShoppingList extends Model { protected $fillable = ['user_id', 'name', 'route_id']; protected $primaryKey = 'list_id'; }
4. 额外检查:SQLite外键启用
确认config/database.php中的sqlite配置已启用外键:
'sqlite' => [ 'driver' => 'sqlite', 'url' => env('DATABASE_URL'), 'database' => env('DB_DATABASE', database_path('database.sqlite')), 'prefix' => '', 'foreign_key_constraints' => env('DB_FOREIGN_KEYS', true), ],
确保foreign_key_constraints为true。
完成以上修复后,重新测试插入操作即可解决外键约束问题。
内容的提问来源于stack exchange,提问作者Velo
相关产品推荐
相关产品推荐

