php - Laravel-SQLSTATE[23000] : Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails

标签 php mysql laravel

我正在 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, CONSTRAINT contents_ct_id_foreign FOREIGN KEY (ct_id) REFERENCES content_types (id)) (SQL: insert into contents (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/

相关文章:

php - 如何在 Laravel 5.2 中使用不同的数据库表列名登录?

php - 在 ubuntu 上运行 html 和 php

php - 在 WordPress 编辑器 HTML 选项卡中嵌入 PHP 命令

php - 使用 GuzzleHTTP 时如何检查端点是否正常工作

PHP/mySQL 下拉框问题

mysql - 根据每组中的一列删除重复项

php - Laravel -- 为什么 `::class` 常量

php - 使用 PHP 更新表中的 MySQL "username"时出现问题

mysql - Sequel Pro/MAMP 在哪里存储本地数据库?

laravel - Vuex 无法使用 npm 安装并给出错误