2017-06-21 83 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'); 
    } 
} 

所以,當我試圖堅持新的內容記錄,我得到的錯誤:

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 *表中,並且您有一個外鍵來關聯這兩者。你可以** var_dump **'$ post-> ID'並確認你在表中有這個值,然後再嘗試創建一個新的* Content *記錄。 – TheFallen

回答

1

貌似$post->ID是空的,是ContentType在數據庫中帶有指定的ID。也許你正在嘗試這樣做?

'ct_id' => $post->id, 

您可以檢查$post變量的內容與dd($post)命令。

如果$post->id爲您提供了正確的值(它不是空的,它存在於表中),然後嘗試使用fillable陣列,其中列出了使用guarded陣列的所有屬性。

相關問題