gpt4 book ai didi

mysql - 违反完整性约束 : 1452 Cannot add or update a child row: a foreign key constraint fails

转载 作者:行者123 更新时间:2023-11-30 21:53:09 25 4
gpt4 key购买 nike

我有用户和项目表。在项目表中,user_id 是外键。我创建了一个项目,当我尝试保存项目详细信息时显示此错误:

SQLSTATE[23000]:违反完整性约束:1452 无法添加或更新子行:外键约束失败(labtestprojects,CONSTRAINT projects_user_id_foreign FOREIGN KEY (user_id) REFERENCES users (id) ON UPDATE CASCADE) (SQL: 插入 Projects (name, description, date, updated_at, created_at) 值 ( e, e, 2017-12-31, 2017-09-19 15:21:06, 2017-09-19 15:21:06))

我该如何解决这个问题?

用户表迁移:

Schema::create('users', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->string('email')->unique();
$table->string('password');
$table->rememberToken();
$table->timestamps();
});

项目表迁移

   Schema::create('projects', function (Blueprint $table) {
$table->increments('id')->unique();
$table->string('name');
$table->text('description');
$table->date('date');
$table->timestamps('date');
});



Schema::table('projects',function(Blueprint $table)
{
$table->integer('user_id')->unsigned();
$table->foreign('user_id')->references('id')->on('users')
->onUpdate('cascade');
});

用户模型:

 public function project()
{
return $this->hasMany('App\Project');
}

项目模型:

  public function user() {
return $this->belongsTo('App\User','id','user_id');
}

Controller :

  public function store(Request $request)
{

$this->validate($request, [
'name' => 'required',
'description' => 'required',
'date' => 'required',
]);


Project::create($request->all());
return redirect()->route('projects.index')
->with('success','Project created successfully');
}

最佳答案

你有两个选择:

  • 第一个:

    $data = $request->all();
    $data['user_id'] = Auth::user()->id;
    Project::create($data);
    //....
  • 第二个:

    Auth::user()->project()->create($request->all());

关于mysql - 违反完整性约束 : 1452 Cannot add or update a child row: a foreign key constraint fails,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46304354/

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