2017-06-21 5 views
0

モデルのデータベースにレコードを永続化しようとするとLaravelでプロジェクトを構築しています。このように設定している:私のコントローラでLaravel - SQLSTATE [23000]:整合性制約違反:1452子行を追加または更新できません:外部キー制約が失敗しました

class Content extends Model 
{ 
    /** 
    * The attributes that are guarded by mass assignable. 
    * 
    * @var array 
    */ 
    protected $guarded = [ 
     'id' 
    ]; 

    public function contentType() 
    { 
     return $this->hasOne('App\ContentType'); 
    } 
} 

私が最初にこのようなCONTENT_TYPESテーブル内のレコードを保存しています:

public function resolveType($type) 
    { 
     return ContentType::firstOrCreate(
      ['name' => $type, 
      'slug' => str_slug($type, '-')] 
     ); 
    } 

そして私は、コンテンツを保存しています:

 Content::create([ 
      'ct_id' => $post->ID, 
      'cms_id' => '', 
      'title' => $post->post_title, 
      'slug' => str_slug($post->post_title, '-'), 
      'excerpt' => $post->post_excerpt, 
      'body' => $this->formatBodyImages($post->post_content), 
      'password' => $post->post_password, 
      'parent_id' => $post->post_parent, 
     ]); 

たContentTypeモデルは、このように設定されています

class ContentType extends Model 
{ 
    /** 
    * The attributes that are guarded by mass assignable. 
    * 
    * @var array 
    */ 
    protected $guarded = [ 
     'id' 
    ]; 

    public function contents() 
    { 
     return $this->hasMany('App\Content', 'ct_id'); 
    } 
} 

だから、私は新しいコンテンツの記録を保持しようとすると、私はエラーを取得:$post->IDが空であるように

SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails (middleton . contents , CONSTRAINT contents_ct_id_foreign FOREIGN KEY (ct_id) REFERENCES content_types (id)) (SQL: insert into contents (cms_id , title , slug , excerpt , body , password , parent_id , updated_at , created_at)

+0

基本的には、* ct_id *の値が* content_types *テーブルに存在せず、これらの2つを関連付ける外部キーがあります。 ** var_dump ** '$ post-> ID'で新しい* Content *レコードを作成しようとする前に、テーブルにこの値があることを確認できますか? – TheFallen

答えて

1

が見えますDBに指定されたIDを持つContentTypeです。多分あなたはこれをしようとしていますか?

'ct_id' => $post->id, 

あなたはdd($post)コマンドで$post変数の内容を確認することができます。

$post->idは(それが空ではありませんし、それがテーブルに存在する)あなたは正しい値を与えた場合は、guardedアレイを使用して、すべての列挙されたプロパティを持つfillable配列を使用してみてください。

関連する問題