モデルのデータベースにレコードを永続化しようとすると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');
}
}
だから、私は新しいコンテンツの記録を保持しようとすると、私はエラーを取得:$post->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 *テーブルに存在せず、これらの2つを関連付ける外部キーがあります。 ** var_dump ** '$ post-> ID'で新しい* Content *レコードを作成しようとする前に、テーブルにこの値があることを確認できますか? – TheFallen