【问题标题】:Laravel 5.1 Relationship - SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint failsLaravel 5.1 关系 - SQLSTATE [23000]:完整性约束违规:1452 无法添加或更新子行:外键约束失败
【发布时间】:2015-10-09 18:28:26
【问题描述】:

我有 3 个表用户、帖子和 cmets。用户和帖子之间的关系还可以。我可以存储新帖子。但是,如果我评论帖子,我会收到以下错误消息:

错误信息

Connection.php 第 631 行中的 QueryException: SQLSTATE[23000]:完整性约束违规:1452 无法添加或更新子行:外键约束失败(blog.comments,CONSTRAINT comments_post_id_foreign FOREIGN KEY (post_id) REFERENCES posts (@987654326 @)) (SQL: 插入comments (body, user_id, updated_at, created_at) 值(新评论, 1, 2015-07-20 14:16:07, 2015-07- 20 14:16:07))

迁移用户

Schema::create('users', function (Blueprint $table) {
        $table->increments('id');
        $table->string('name');
        $table->string('email')->unique();
        $table->string('password', 60);
        $table->rememberToken();
        $table->timestamps();
    });

迁移帖子

Schema::create( 'posts', function ( Blueprint $table ) {
        $table->increments( 'id' );
        $table->integer( 'user_id' )->unsigned();
        $table->string( 'title' );
        $table->text( 'body' );
        $table->timestamps();

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

迁移cmets

Schema::create('comments', function (Blueprint $table) {
        $table->increments( 'id' );
        $table->integer( 'user_id' )->unsigned();
        $table->integer( 'post_id' )->unsigned();
        $table->text( 'body' );
        $table->timestamps();

        $table->foreign( 'user_id' )->references( 'id' )->on( 'users' );
        $table->foreign( 'post_id' )->references( 'id' )->on( 'posts' );
    });

模型用户

protected $fillable = [
    'name',
    'email',
    'password'
];

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

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

模特发帖

protected $fillable = [
    'title',
    'body'
];

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

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

模型评论

protected $fillable = [
    'body'
];

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

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

评论控制器

public function store( CommentRequest $request ) {
    Auth::user()->comments()->create( $request->all() );
    return redirect()->back();
}

PostController $request->all()

"_token" => "TzdItNKU3TChVg50vAqdy1CYCrIR562l4Wv2z6ef"
"title" => "New Post"
"body" => "New text"

CommentController $request->all()

"_token" => "TzdItNKU3TChVg50vAqdy1CYCrIR562l4Wv2z6ef"
"body" => "New Comment"

【问题讨论】:

    标签: laravel foreign-keys constraints relationship


    【解决方案1】:

    我在互联网上发现了这个技巧,在这种情况下效果很好。

    DB::statement('SET FOREIGN_KEY_CHECKS=0;');
    
    Schema::table('foo_products', function(Blueprint $table)
    {
        $table->unsignedInteger('foo_type_id');
        $table->foreign('foo_type_id')->references('id')->on('foo_types');
    });
    DB::statement('SET FOREIGN_KEY_CHECKS=1;');
    

    您只需在架构之前禁用外键检查,然后在之后启用它。

    【讨论】:

      【解决方案2】:

      您的 Comment 模型通过 post_id 字段与 Post 模型相关,并且该字段在数据库。因此,该表中的所有记录都需要填写该字段。此外,由于您对该字段有外键约束,因此它始终需要指向 Post 表中的现有行。

      在您的情况下,似乎任何数据传递给您的 Auth::user()->cmets()->create(),它要么不包含 post_id 字段或 post_id 字段未在您的 Comment 模型中标记为 fillable

      我建议您首先检查控制器方法中的 $request->all() 返回什么。如果该字段存在,请将 post_id 添加到 Comment 模型中的可填写 字段列表中:

      protected $fillable = [ /** list all fields that should be fillable by create/update methods **/ ];
      

      【讨论】:

      • PostController $request->all() 不返回 user_id 并且它不在 fillable 数组中。但它有效。但是,post_id 不存在。我已经编辑了我的帖子。我从 PostControllerCommentController 添加了 fillable 数组和 $request->all()
      • 之所以有效,是因为您正在对用户调用“->cmets()”,因此 Eloquent 知道要为这些 cmets 设置什么 user_id。但是post需要手动链接到cmets。
      • 如何巧妙地做到这一点?像这样: public function store( CommentRequest $request, $postId ) { Auth::user()->cmets()->create( $request->all() );返回重定向()->返回(); } 并将 postId 附加到请求中?还是有更好的方法?
      • 这取决于您存储 post_id 的位置。它来自 URL 吗?还是在请求正文中?
      • 你是如何定义这个控制器动作的路由的?
      猜你喜欢
      • 2014-01-09
      • 2017-04-13
      • 2017-11-23
      • 1970-01-01
      • 2018-02-12
      • 2021-09-29
      相关资源
      最近更新 更多