gpt4 book ai didi

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

转载 作者:搜寻专家 更新时间:2023-10-31 22:00:37 24 4
gpt4 key购买 nike

我知道这是一个常见问题,但不知道这里出了什么问题。如您所见,有这个 //return $user 并且它显示了一个有效的 id。也在数据库中进行了检查。

        $user = new User;
$user->first_name = $data['first_name'];
$user->last_name = $data['last_name'];
$user->email = $data['email'];
$user->phone_no = $data['phone_no'];
$user->created_from = 'Web App';
$user->save();
// return $user;
Session::put('user_id',$user->id);
// return $user->id;
$address = new Address;
$address->user_id = $user->id;
$address->first_name = $data['receiver_first_name'];
$address->last_name = $data['receiver_last_name'];
$address->email = $data['receiver_email'];
$address->address_line_1 = $data['receiver_address_line_1'];
$address->address_line_2 = $data['receiver_address_line_2'];
$address->landmark = $data['receiver_landmark'];
$address->pincode = $data['receiver_pincode'];
$address->phone_no = $data['receiver_phone_no'];
$address->created_from = 'Web App';
$address->save();

这里是迁移:这是用户迁移

<?php

use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class CreateUsersTable extends Migration {

/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('users', function($table){
$table->increments('id');
$table->string('first_name');
$table->string('last_name');
$table->string('email');
$table->string('phone_no', 20)->nullable();
$table->string('password')->nullable();
$table->string('remember_token', 100);
$table->date('date_of_birth')->nullable();
$table->string('created_from');

$table->timestamps();
$table->softDeletes();
});
}

/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('users');
}

地址

public function up()
{
Schema::create('addresses', function($table){
$table->increments('id');
$table->integer('user_id')->unsigned();
$table->string('first_name');
$table->string('last_name');
$table->string('email');
$table->string('address_line_1');
$table->string('address_line_2')->nullable();
$table->string('landmark')->nullable();
$table->string('city')->nullable();
$table->string('state')->nullable();
$table->string('phone_no', 13);
$table->integer('pincode');
$table->string('created_from');

$table->timestamps();
$table->softDeletes();

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

如果有帮助,这里是错误的屏幕截图。 Screenshot of error

最佳答案

根据报错信息,你的错误是由于在adresses.user_id中插入了一个值(FK to src.id),而这个值在src.id中是不存在的。
在示例中,您尝试在 adresses.user_id 中插入 29,检查 SELECT id FROM src WHERE id=29 是否返回任何结果。如果不是,那就是你的问题。

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

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