我正在 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');
}
}
在我的控制器中,我首先将记录保存在 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]: 完整性约束违规:1452 无法添加或更新子行:外键约束失败 (
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
array 和 using guarded
array.properties 的所有列出的属性。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句