我正在 Laravel 中构建一个项目,尝试在数据库中保存我设置的模型内容的记录,如下所示:
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');
}
}
在我的 Controller 中,我首先将记录保存在 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
为空,并且数据库中有具有指定ID的ContentType
。也许您正在尝试这样做?
'ct_id' => $post->id,
您可以使用dd($post)
命令检查$post
变量的内容。
如果 $post->id
为您提供正确的值(它不为空并且存在于表中),则尝试使用 fillable
数组以及所有列出的属性使用 protected
数组。
关于php - Laravel-SQLSTATE[23000] : Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44669154/