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

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 DS18B20内部ADC模数转换器
  • ¥15 做个有关计算的小程序
  • ¥15 MPI读取tif文件无法正常给各进程分配路径
  • ¥15 如何用MATLAB实现以下三个公式(有相互嵌套)
  • ¥30 关于#算法#的问题:运用EViews第九版本进行一系列计量经济学的时间数列数据回归分析预测问题 求各位帮我解答一下
  • ¥15 setInterval 页面闪烁,怎么解决
  • ¥15 如何让企业微信机器人实现消息汇总整合
  • ¥50 关于#ui#的问题:做yolov8的ui界面出现的问题
  • ¥15 如何用Python爬取各高校教师公开的教育和工作经历
  • ¥15 TLE9879QXA40 电机驱动