我在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
, CONSTRAINTcontents_ct_id_foreign
FOREIGN KEY (ct_id
) REFERENCEScontent_types
(id
)) (SQL: insert intocontents
(cms_id
,title
,slug
,excerpt
,body
,password
,parent_id
,updated_at
,created_at
)
它基本上說,* ct_id *的值不存在於* content_types *表中,並且您有一個外鍵來關聯這兩者。你可以** var_dump **'$ post-> ID'並確認你在表中有這個值,然後再嘗試創建一個新的* Content *記錄。 – TheFallen