![](/img/trans.png)
[英]Error: Integrity constraint violation: 1052 when Join in Laravel Eloquent
[英]Laravel 5.6 Eloquent integrity constraint violation when saving quiz record
我目前正在使用Laravel 5.6開發測驗應用程序,並且在保存新測驗記錄時遇到了麻煩。
插入的兩個表是quizzes
和user_quizzes
。 quizzes
表包含一些基本測驗數據,例如:
user_quizzes
表包含兩個外鍵,以引用哪個測驗屬於特定用戶。
當插入到user_quizzes
表中時,該錯誤是違反完整性約束的。 它成功插入quiz_id
但user_id
保留為NULL。 我不確定如何確保在使用Eloquent時也插入了user_id
。
完整的錯誤是:
SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'user_id' cannot be null (SQL: insert into `user_quizzes` (`quiz_id`, `user_id`) values (6, ))
我正在使用QuizController
, Quiz Model
和User Model
來保存記錄。 這是我在QuizController
中的store()
方法:
public function store(Request $request)
{
$validator = $request->validate([
'quiz_name' => 'required|max:30',
'quiz_description' => 'required|max:500'
]);
$quiz = new Quiz(
[
'quiz_name' => $request->get('quiz_name'),
'quiz_description' => $request->get('quiz_description'),
'active' => '0',
'quiz_pin' => '5555', // hard coded for now
]
);
$quiz->save();
$user = new User;
$user->quizzes()->save($quiz);
return redirect()->route('quiz_host.dashboard.manage-quizzes')->with('quizCreated', 'Whoa ' . Auth::user()->username . ', you have created a quiz! Now it\'s time to add some questions');
}
我的User
模型如下:
<?php
namespace App\Models;
use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;
class User extends Authenticatable
{
use Notifiable;
/**
* The attributes that are mass assignable.
*
* @var array
*/
protected $fillable = [
'username', 'email', 'password',
];
/**
* The attributes that should be hidden for arrays.
*
* @var array
*/
protected $hidden = [
'password', 'remember_token',
];
public function activation()
{
return $this->hasOne('App\Models\Activation');
}
public function profile()
{
return $this->hasOne('App\Models\Profile');
}
public function quizzes()
{
return $this->belongsToMany(Quiz::class, 'user_quizzes', 'user_id', 'quiz_id');
}
}
和我的Quiz
模型:
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class Quiz extends Model
{
protected $table = 'quizzes';
protected $fillable = ['quiz_name', 'quiz_description', 'active', 'quiz_pin'];
public function user()
{
return $this->belongsToMany(User::class, 'user_quizzes', 'quiz_id', 'user_id');
}
}
關於我在做什么錯的任何指導將不勝感激。
這是您的控制器:
QuizController.php
public function store(Request $request)
{
// your validations.
// Storing the quiz.
$quiz->save();
// User instance.
$user = new User;
// Storing the relationship.
$user->quizzes()->save($quiz);
// Returning the view.
return redirect()->route('quiz_host.dashboard.manage-quizzes')->with('quizCreated', 'Whoa ' . Auth::user()->username . ', you have created a quiz! Now it\'s time to add some questions');
}
現在,這里的問題與$user
對象有關。
執行此操作時:
$user = new User;
您正在創建User
類的實例,但是該對象尚未持久保存到數據庫中,這意味着該對象還沒有id
。 您可以通過dd($user->id)
來確認,這將返回null
。
這就是為什么當您這樣做時:
$user->quizzes()->save($quiz);
它將引發SQL錯誤,因為您正在調用將$user
對象的$primaryKey
( id
)存儲在數據透視表中的方法。 但是考慮到$user
對象沒有主鍵,它試圖存儲一個null
值。
現在,我真的不知道您的“用例”是什么,但我將假定$user
是已登錄的$user
,因此要正確關聯該關系,請替換為:
// creating a User instance.
$user = new User;
有了這個:
// Logged-in user.
$user = auth()->user();
這將使用authfacade獲取實際的登錄用戶並返回對象。 鑒於該用戶是注冊用戶,因此將具有正確的id
。
如果您的用例不同,則將測驗與其他用戶相關聯,請執行以下操作:
// Some other user
$user = User::find($someId); // $user = User::find(5); for example
或創建一個全新的User
實例並將測驗與之關聯:
// A new User
$user = new User;
$user->fill($someData);
$user-save(); // this will assign a primary key (id) to the object.
現在,您可以將相關模型附加到它。
您的users m--------m quizzes
是多對多關系 。
因此,如文檔所述,在兩個對象之間存儲關系的正確方法是attach()
方法:
$user->quizzes()->attach($quiz->id);
此方法將使用$user
和$quiz
對象的ID在中間表(數據透視表)中創建一條記錄。
為了明確起見, new User
將僅創建用戶模型對象,但仍未提交給DB。
當我們嘗試調用$user->quizzes()->save($quiz)
,它將嘗試在user_quizzes數據透視表中添加一個條目,但是user_id為空,因為仍未創建用戶。
因此,必須先在數據庫中通過調用$user->save()
創建用戶條目,然后才能將其添加到數據透視表中。
$quiz->save();
$user = new User;
$user->save();
$user->quizzes()->save($quiz);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.