gpt4 book ai didi

laravel - SQLSTATE[23000] : Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails Laravel

转载 作者:行者123 更新时间:2023-12-01 18:44:37 31 4
gpt4 key购买 nike

我有两张表,一张用于用户,一张用于新项目。我在项目表的用户表中引用了 id。

 public function up()
{
Schema::create('items', function (Blueprint $table) {
$table->increments('id');
$table->integer('user_id')->unsigned();
$table->string('item_title');
$table->timestamps();
});

Schema::table('items', function($table) {
$table->foreign('user_id')->references('id')->on('users');
});

这是我用于添加新项目的 Controller

public function storeItem(Request $request){
$user = Auth::user();

$item = new Item([
'user_id' => $user->id,
'item_title' => $request->input('title'),
]);

$item->save();
}

但是当我提交表单时,出现此错误SQLSTATE[23000]:违反完整性约束:1452 无法添加或更新子行:外键约束失败(database.items, CONSTRAINTitems_user_id_foreign外键 (user_id) 引用users(id))

有什么想法吗?

最佳答案

好吧,首先尝试修复您的迁移:

public function up()
{
Schema::create('items', function (Blueprint $table) {
$table->increments('id');
$table->integer('user_id')->unsigned();
$table->string('title');
$table->timestamps();

$table->foreign('user_id')->references('id')->on('users')->onDelete('restrict');
});
}

public function down()
{
Schema::drop('items');
}

运行$ php artisan migrate:refresh

Note: using prefix "item_" is looking bad, you already have table named as item(s), so drop the prefix... name your columns properly

Controller (方法)

public function storeItem(Request $request, App\Item $item) 
{
$user = $request->user(); // get current user making the request

$data = array_merge($request->only(['title']), ['user_id' => $user->id]);
$newItem = $item->create($data);
//$newItem has instance of your created item
}

Note: remember to correctly fill $fillable array in your Item model (in this case it should have only 'title' and 'user_id')

关于laravel - SQLSTATE[23000] : Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails Laravel,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40865782/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com