![](/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.