![](/img/trans.png)
[英]Laravel Create Eloquent Instance from ManyToOne Relationship Error SQLSTATE[23000]
[英]Laravel 5.2 one to one relationship gives an error mesg “SQLSTATE[23000]:” after form submission
我在laravel 5.2中创建了两个表,一个表称为“用户”,另一个表称为“ artists_details”,它们具有一对一的关系。 用户表的架构如下
Schema::create('users', function (Blueprint $table) {
$table->engine = 'InnoDB';
$table->increments('id');
$table->boolean('admin')->nullable();
$table->boolean('manager')->nullable();
$table->string('name');
$table->string('email')->unique();
$table->string('password', 60);
$table->rememberToken();
$table->timestamps();
});
并且Artists表的架构如下
Schema::create('artists_details', function (Blueprint $table) {
$table->engine = 'InnoDB';
$table->integer('user_id')->unsigned();
$table->string('artists_image_path');
$table->string('name');
$table->integer('phone_no');
$table->integer('passport');
$table->string('city');
$table->string('county');
$table->string('facebook_name');
$table->string('twitter_handle');
$table->string('email');
$table->string('alternative_email');
$table->string('website');
$table->text('biography');
$table->timestamps();
$table->foreign('user_id')
->references('id')
->on('users')
->onDelete('CASCADE');
});
我已经在模型中指出了以下关系用户模型
public function artists_relation()
{
return $this->hasOne('App\artists_details_model');
}
并在artist_details_model上如下
public function user_artist_details()
{
return $this->belongsTo('App\User');
}
在控制器中处理表单提交的php代码如下
public function artists_details_store(Request $request)
{
$input = \Request::all();
$file = $request->file('file');
$name = time(). $file->getClientOriginalName();
$file->move('artists_image/photo', $name);
$artists_input = new artists_details_model;
$artists_input->artists_image_path = 'artists_image/photo/'. $name;
$artists_input->name = $input['name'];
$artists_input->phone_no = $input['phone_no'];
$artists_input->passport = $input['passport'];
$artists_input->city = $input['city'];
$artists_input->county = $input['county'];
$artists_input->facebook_name = $input['facebook_name'];
$artists_input->twitter_handle = $input['twitter_handle'];
$artists_input->email = $input['email'];
$artists_input->alternative_email = $input['alternative_email'];
$artists_input->website = $input['website'];
$artists_input->biography = $input['biography'];
$artists_input->save();
return redirect('create');
}
当我单击提交按钮时,出现以下错误信息
Connection.php第669行的QueryException:
SQLSTATE [23000]:违反完整性约束:1452无法添加或更新子行:外键约束失败
我似乎看不到我要去哪里或问题出在哪里
对于表“ artists_details”,您提到的是
$table->foreign('user_id') ->references('id') ->on('users')
因此,每当您尝试将详细信息保存在“ artists_details”中时,都需要提供“ user_id”,否则将无法保存信息。
您需要传递“ UserID”作为隐藏参数,或者如果UserID保存在会话中,则需要从会话中检索它。
您似乎没有在表单中包含外键{user_id}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.