php - Laravel 5.6 保存测验记录时 Eloquent 完整性约束违规

标签 php mysql laravel eloquent

我目前正在使用 Laravel 5.6 开发一个测验应用程序,但在保存新的测验记录时遇到问题。

要插入的两个表是quizzesuser_quizzesquizzes 表包含一些基本的测验数据,例如:

  • 测验名称
  • 测验描述
  • quiz_pin
  • 活跃

user_quizzes 表包含两个外键,用于引用哪个测验属于特定用户。

  • 用户 ID
  • 测验 ID

该错误是插入到 user_quizzes 表时违反完整性约束。它成功插入 quiz_iduser_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, ))

我正在使用QuizControllerQuiz ModelUser 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');

    }

我的用户模型如下:

<?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');
    }
}

和我的测验模型:

<?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');
    }
}

任何关于我做错了什么的指导将不胜感激。

最佳答案

检查您的代码

这是您的 Controller :

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 是登录用户,因此为了正确关联关系,请替换以下内容:

    // creating a User instance.
    $user = new User;

这样:

    // Logged-in user.
    $user = auth()->user();

这将使用 auth 外观来获取实际登录的用户并返回对象。鉴于这是一个注册用户,它将有一个正确的 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.

现在您可以将相关模型附加到其上。

<小时/>

旁注

您的用户 m--------m 测验many to many relationship

所以,如the documentation says ,存储两个对象之间关系的正确方法是 attach() 方法:

    $user->quizzes()->attach($quiz->id);

此方法将使用 $user$quiz 对象的 ID 在中间表(数据透视表)中创建一条记录。

关于php - Laravel 5.6 保存测验记录时 Eloquent 完整性约束违规,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49113071/

相关文章:

mysql - 无法添加或更新子行: a foreign key constraint fails (Laravel)

PHP - 调用未定义函数 http_inflate()

php - 如何防止在 php html 中包装 div

php - mysql-php 使用 if 条件进行计数

java - 准备好的语句需要重新准备

laravel - vue.config.js 到 (laravel) webpack.mix.js

php - Laravel上传文件无法写入目录

php - 如果数字不正确,Twilio PHP Lookup API 不会返回任何响应?

php - 如何使用日期作为新列名

mysql - 为什么我收到 errno : 150 "Foreign key constraint is incorrectly formed"?