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 电脑出问题了,说是usbmom注册表没
  • ¥20 需要步骤截图(标签-服务器|关键词-map)
  • ¥50 gki vendor hook
  • ¥15 centos7中sudo命令无法使用
  • ¥15 灰狼算法和蚁群算法如何结合
  • ¥15 这是一个利用ESP32自带按键和LED控制的录像代码,编译过程出现问题,请解决并且指出错误,指导如何处理 ,协助完成代码并上传代码
  • ¥20 stm32f103,hal库 hal_usart_receive函数接收不到数据。
  • ¥20 求结果和代码,sas利用OPTEX程序和D-efficiency生成正交集
  • ¥50 adb连接不到手机是怎么回事?
  • ¥20 抓取数据时发生错误: get_mooncake_data() missing 1 required positional argument: 'driver'的问题,怎么改出正确的爬虫代码?