go-gorm / gorm

The fantastic ORM library for Golang, aims to be developer friendly
https://gorm.io
MIT License
36.97k stars 3.93k forks source link

Question About Composite Index #5512

Open JiawenFan810 opened 2 years ago

JiawenFan810 commented 2 years ago

Your Question

type BaseModel struct {
   ID                uint                `gorm:"primaryKey`
   CreatedAt    time.time
   UpdatedAt   time.time
   DeletedAt    gorm.DeletedAt    `gorm:"index"`
}

type User struct {
   BaseModel
   Name         string   `gorm:"index`
}

BaseModel is used in many other models as well. What can I do if I want to use composite index for User.DeletedAt and User.Name? The only solution I came about is not to use BaseModel embedded and use the following directly.


type User struct {
   ID                uint                `gorm:"primaryKey`
   CreatedAt    time.time
   UpdatedAt   time.time
   DeletedAt    gorm.DeletedAt    `gorm:"index:idx_users_name_deleted_at"`
   Name           string                    `gorm:"index:idx_users_name_deleted_at`
}

Is there a way to add the composite index to User as well as using the embedded BaseModel? I tried to use db.Migrator().CreateIndex(), but found that CreateIndex() method also needs the gorm tag in the model.

Thank you!

github-actions[bot] commented 1 year ago

This issue has been automatically marked as stale because it has been open 360 days with no activity. Remove stale label or comment or this will be closed in 180 days

patrickdemers6 commented 1 year ago

@jinzhu any insight on this?

hasa1K commented 5 months ago

Is there any progress on this issue?