【发布时间】:2018-03-12 15:53:06
【问题描述】:
我目前正在使用 Laravel 5.6 开发一个测验应用程序,但无法保存新的测验记录。
要插入的两个表是quizzes 和user_quizzes。 quizzes 表包含一些基本的测验数据,例如:
- 测验名称
- quiz_description
- quiz_pin
- 有效
user_quizzes 表包含两个外键,用于引用哪个测验属于特定用户。
- user_id
- quiz_id
错误是插入user_quizzes 表时违反完整性约束。它成功插入了quiz_id,但user_id 保留为NULL。我不确定如何确保 user_id 在我使用 Eloquent 时也被插入。
完整的错误是:
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');
}
}
任何关于我做错了什么的指导将不胜感激。
【问题讨论】:
-
先创建用户,再附加测验。
-
我很确定
$quiz->save();和$user->quizzes()->save($quiz);都在数据库中插入了一条新记录;如果是这种情况,您只需省略第一个$quiz->save()。否则,请先保存您的User,然后将测验的user_id设置为保存的用户,然后再调用$quiz->save(); -
谢谢你们,我将当前用户设置为
$user = Auth::user(),然后省略了$quiz->save(),然后离开$user->quizzes()->save($quiz),它现在可以工作了。
标签: php mysql laravel eloquent