【问题标题】:Laravel - Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint failsLaravel - 完整性约束违规:1452 无法添加或更新子行:外键约束失败
【发布时间】:2020-08-13 06:58:53
【问题描述】:

我目前正在通过个人项目学习 Laravel。

上下文

在类似博客的应用程序中,我需要将文章链接到其作者。当我保存文章时,我收到以下错误。

错误

SQLSTATE[23000]:完整性约束违规:1452 无法添加或更新子行:外键约束失败(parabolica-dev.articles,CONSTRAINT articles_user_id_foreign FOREIGN KEY(user_id)参考users (id)) (SQL: 插入articles (title, content, excerpt, updated_at, created_at) 值 (rgergregerg, regergergregerg, regregregregreg, 2020-04-29 09: 55:12, 2020-04-29 09:55:12))

型号

文章

class Article extends Model
{
    protected $fillable = ['title', 'content', 'excerpt', 'user_id'];

    public function user() {
        return $this->belongsTo('App\User');
    }
}

用户

class User extends Authenticatable
{
    protected $fillable = [
        'name', 'email', 'password',
    ];

    public function article()
    {
        return $this->hasMany('App\Article');
    }
}

迁移

用户

class CreateUsersTable extends Migration
{
    public function up()
    {
        Schema::create('users', function (Blueprint $table) {
            $table->id();
            $table->string('name');
            $table->string('email')->unique();
            $table->timestamp('email_verified_at')->nullable();
            $table->string('password');
            $table->rememberToken();
            $table->timestamps();
        });
    }

    public function down()
    {
        Schema::dropIfExists('users');
    }
}

文章

class CreateArticlesTable extends Migration
{
    public function up()
    {
        Schema::create('articles', function (Blueprint $table) {
            $table->id();
            $table->timestamps();
            $table->string('title');
            $table->text('excerpt');
            $table->text('content');
            $table->string('type');
            $table->string('status');

            // Relationship between article and user

            $table->bigInteger('user_id')->unsigned();
            $table->foreign('user_id')->references('id')->on('users');
        });
    }

    public function down()
    {
        Schema::dropIfExists('articles');
    }
}

控制器

文章控制器

class ArticleController extends Controller
{
    public function store(StoreArticle $request)
    {
        $validatedData = $request->validated();

        $user = Auth::user()->id;
        $article = Article::create($validatedData);
        $article->user_id = $user;
        $request->session()->flash('status', 'Article was created!');

        return redirect()->route('articles.show', ['article' => $article->id]);
    }
}

尝试的解决方案

  • 在我的 Article 模型中将 user_id 添加到 $fillable 数组中,我仍然收到错误。
  • 在我的迁移中将 nullable() 方法添加到 user_id。保存文章没有错误消息,但之后 user_id 在我的表中记录为空。

根据我的发现,这些是跨 SO / LaravelCast 提出最多的 2 个解决方案。关于我做错了什么有什么建议吗?

谢谢你帮助我!

【问题讨论】:

    标签: php mysql laravel


    【解决方案1】:

    create 方法创建并保存模型的新实例。由于该模型此时不包含用户 ID,因此它失败了。

    您可以通过在模型的可填充数组中添加 user_id 来解决此问题,并在创建模型之前将用户 ID 添加到 $validatedData 数组中。

    或者,您还可以使用 new 关键字创建模型的新实例,设置所有数据并在完成后明确保存:

    $article = new Article($validatedData);
    $article->user()->associate( Auth::user() );
    $article->save();
    

    【讨论】:

      【解决方案2】:

      你必须改变这三行。您插入一行,但当时 user_id 为空。这就是它显示错误的原因,因为您分配的 user_id 字段不可为空。

      $article = new Article;
      $article->fill($validatedData); 
      $article->user_id = Auth::user()->id;
      $article->save();
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2014-03-12
        • 2016-10-27
        • 2015-05-25
        • 1970-01-01
        • 2014-01-09
        • 2017-04-13
        相关资源
        最近更新 更多