1

I have entity in gorm

type Category struct {
    ID       string    `json:"id"`
    Name     string    `json:"name"`
    ParentID string    `json:"parent_id" gorm:"default:null`
    Parent   *Category `gorm:"foreignKey:ParentID"`
}

but when I want to save



func SaveItem(ctx *fiber.Ctx) error {
    db := database.DbConn
    emptyParent := Category{
        ID: uuid.NullUUID{}.UUID.String(),
    }
    dto := new(Category)
    if err := ctx.BodyParser(dto); err != nil {
        ctx.Status(503).SendString(err.Error())
        return err
    }

    itemDb := new(Category)
    rows := []Category{}
    db.Where("ID = ?", dto.ID).Find(&rows)
    if len(rows) > 0 {
        itemDb = &rows[0]
        itemDb.Name = dto.Name
        rows := []Category{}
        db.Where("ID = ?", dto.ParentID).Find(&rows)
        if len(rows) > 0 {
            parent := rows[0]
            itemDb.Parent = &parent
        } else {
            itemDb.Parent = &emptyParent
        }
        res := db.Save(itemDb)
        err := res.Error
        if err != nil {
            ctx.Status(503).SendString(err.Error())
        }
        return ctx.JSON(&itemDb)
    } else {
        dto.ID = uuid.NewString()
        rows := []Category{}
        db.Where("ID = ?", dto.ParentID).Find(&rows)
        if len(rows) > 0 {
            parent := rows[0]
            dto.Parent = &parent
        } else {
            dto.Parent = &emptyParent
        }
        res := db.Create(&dto)
        err := res.Error
        if err != nil {
            ctx.Status(503).SendString(err.Error())
        }

        return ctx.JSON(&dto)
    }

}

it cause error "insert or update on table "categories" violates foreign key constraint "fk_categories_parent"

question what is wrong ? Who can help me?

in the example below I tried my best. I expect code example.Thank you!

1
  • You are omitting multiple error checks. Handle all possible errors and you will find what is wrong Commented Jan 18, 2024 at 7:35

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.