duannai5858 2017-06-21 07:12
浏览 50
已采纳

Laravel - SQLSTATE [23000]:完整性约束违规:1452无法添加或更新子行:外键约束失败

I am building a project in Laravel on trying to persist a record in the database for the model Content that I have set up like this:

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');
    }
}

In my controller I am first saving the record in the content_types table like this:

    public function resolveType($type)
    {
        return ContentType::firstOrCreate(
          ['name' => $type,
          'slug' => str_slug($type, '-')]
        );
    }

And then I am saving the content:

        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,
        ]);

The ContentType model is set up like this:

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');
    }
}

So, when I try to persist new content record, I get the error:

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)

  • 写回答

1条回答 默认 最新

  • duanpeng1532 2017-06-21 07:26
    关注

    Looks like $post->ID is empty and there is ContentType with specified ID in the DB. Maybe you're trying to do this?

    'ct_id' => $post->id,
    

    You can check contents of the $post variable with dd($post) command.

    If $post->id gives you correct value (it's not empty and it exists in the table), then try to use fillable array with all listed properties of using guarded array.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 关于#windows#的问题:怎么用WIN 11系统的电脑 克隆WIN NT3.51-4.0系统的硬盘
  • ¥15 matlab有关常微分方程的问题求解决
  • ¥15 perl MISA分析p3_in脚本出错
  • ¥15 k8s部署jupyterlab,jupyterlab保存不了文件
  • ¥15 ubuntu虚拟机打包apk错误
  • ¥199 rust编程架构设计的方案 有偿
  • ¥15 回答4f系统的像差计算
  • ¥15 java如何提取出pdf里的文字?
  • ¥100 求三轴之间相互配合画圆以及直线的算法
  • ¥100 c语言,请帮蒟蒻写一个题的范例作参考