Open yanjinbin opened 7 months ago
type Option func(gorm.DB) gorm.DB
type Model struct {
ID int64 gorm:"column:id;primaryKey" json:"id"
Name string gorm:"column:name" json:"name"
}
// --------------------- db infrastructure start ---------------------
func (ModelData) TableName() string { return "xes_matrix_register_component" }
type ModelData struct { db *gorm.DB }
func (d ModelData) optionDB(ctx context.Context, opts ...Option) gorm.DB { db := d.db.Table(d.TableName()).WithContext(ctx) for _, opt := range opts { db = opt(db) } return db }
// --------------------- db infrastructure end ---------------------
// --------------------- widgets start ---------------------
func (d ModelData) WithStaffId(staffId int64) Option { return func(db gorm.DB) *gorm.DB { return db.Where("staff_id = ?", staffId) } }
func (d ModelData) WithUserId(userId int64) Option { return func(db gorm.DB) *gorm.DB { return db.Where("user_id = ?", userId) } }
func (d ModelData) WithLimit(limit int) Option { return func(db gorm.DB) *gorm.DB { return db.Limit(limit) } }
func (d ModelData) WithOffset(offset int) Option { return func(db gorm.DB) *gorm.DB { return db.Offset(offset) } }
func (d ModelData) WithCond(cond Model) Option { return func(db gorm.DB) gorm.DB { return db.Where(cond) } }
// --------------------- widgets end ---------------------
// --------------------- repo start ---------------------
func (d *ModelData) GetList(ctx context.Context, opts ...Option) ([]Model, error) { models := make([]Model, 0) tx := d.optionDB(ctx, opts...).Table(new(ModelData).TableName()).Find(&models) if tx.Error != nil { return nil, tx.Error } return models, nil }
func main() {
md := new(ModelData)
list, _ := md.GetList(context.Background(),
md.WithStaffId(1),
md.WithUserId(2),
md.WithLimit(3),
md.WithOffset(4),
)
fmt.Println(list)
}
use this, you can add any 「where func」 you want
Your Question
table user ( id, name ) table staff ( id, user_id, name) table foo ( id, user_id, staff_id ) table operations ( id, user_id, staff_id )
query foo by user_id will be like
query operations by user_id will be like
again and again
but I don't repeat append where user_id = 1 condition
The document you expected this should be explained
Expected answer
expected sql will be like
so does any feature can support it ?