Laravel - SQLSTATE [23000]:完整性约束违规:1452无法添加或更新子行:外键约束失败
问题描述:
我在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
)
答
貌似$post->ID
是空的,是ContentType
在数据库中带有指定的ID。也许你正在尝试这样做?
'ct_id' => $post->id,
您可以检查$post
变量的内容与dd($post)
命令。
如果$post->id
为您提供了正确的值(它不是空的,它存在于表中),然后尝试使用fillable
阵列,其中列出了使用guarded
阵列的所有属性。
它基本上说,* ct_id *的值不存在于* content_types *表中,并且您有一个外键来关联这两者。你可以** var_dump **'$ post-> ID'并确认你在表中有这个值,然后再尝试创建一个新的* Content *记录。 – TheFallen