2016-04-28 13 views
1

mysqlデータベースにデータを挿入中にエラーが発生しました。以前の質問の回答がstackoverflowにありました。protected $fillableをモデルファイルに入れましたが、データの挿入中にエラーが発生しました。

最初のエントリテーブルを作成しているときにエラーが発生していないのに、新しいエントリにエラーが表示されているとき。

SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails (`app`.`articles`, CONSTRAINT `articles_ibfk_1` FOREIGN KEY (`article_id`) REFERENCES `users` (`id`)) (SQL: insert into `articles` (`article_head`, `article_body`) values (abkskfbasfbv, zbfvaksdvaskdvjsdc 
)) 

Article.php

<?php 

namespace App; 

use Illuminate\Database\Eloquent\Model; 

class Article extends Model 
{ 
    protected $fillable = [ 
     'article_head', 'article_body', 
    ]; 
    public $timestamps = false; 
} 

マイグレーションファイル

<?php 

use Illuminate\Database\Migrations\Migration; 
use Illuminate\Database\Schema\Blueprint; 

class CreateArticlesTable extends Migration { 

    /** 
    * Run the migrations. 
    * 
    * @return void 
    */ 
    public function up() 
    { 
     Schema::create('articles', function(Blueprint $table) 
     { 
      $table->increments('article_id'); 
      $table->string('article_head', 500); 
      $table->string('article_body', 10000); 
      $table->dateTime('created_on'); 
      $table->timestamps(); 
     }); 
    } 


    /** 
    * Reverse the migrations. 
    * 
    * @return void 
    */ 
    public function down() 
    { 
     Schema::drop('articles'); 
    } 

} 

2016_04_27_181606_add_foreign_keys_to_articles_table.php

<?php 

use Illuminate\Database\Migrations\Migration; 
use Illuminate\Database\Schema\Blueprint; 

class AddForeignKeysToArticlesTable extends Migration { 

    /** 
    * Run the migrations. 
    * 
    * @return void 
    */ 
    public function up() 
    { 
     Schema::table('articles', function(Blueprint $table) 
     { 
      $table->foreign('article_id', 'articles_ibfk_1')->references('id')->on('users')->onUpdate('RESTRICT')->onDelete('RESTRICT'); 
     }); 
    } 


    /** 
    * Reverse the migrations. 
    * 
    * @return void 
    */ 
    public function down() 
    { 
     Schema::table('articles', function(Blueprint $table) 
     { 
      $table->dropForeign('articles_ibfk_1'); 
     }); 
    } 

} 

+1

[整合性制約違反:1452子行を追加または更新できません](http://stackoverflow.com/questions/14063652/integrity-constraint-violation-1452-cannot-add-or-update- a-child-row) – e4c5

+0

だから私は私の記事のテーブルにユーザーテーブルと同じID列を追加する必要がありますか? –

答えて

0

挿入するテーブル記事のarticle_idの値がテーブルユーザーに存在しないか、テーブルユーザーの記事の値が挿入されていないことを意味します。テーブルの上のユーザーの列のarticle_idの値は、テーブルの上のユーザーIDの値に依存していることを念頭に置いてベア

+0

私の記事テーブルにid列を追加する –

+0

はい、それを試してみてください! –

+0

いいえ、その作業していない –

1

は、あなたの記事のモデルで

protected $primaryKey = "article_id"; 

を入れてください。

+0

記事テーブルへの最初のエントリを作成しているときにエラーが発生していないのに、新しいエントリにエラーが表示されているとき –

関連する問題