go-gorm / gorm

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

how do hook before select query on target tables #6939

Open yanjinbin opened 7 months ago

yanjinbin commented 7 months ago

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

select * from foo where user_id = 1 and staff_id =1

query operations by user_id will be like

select * from operations where user_id = 1 and staff_id =1

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


select * from foo   staff_id = 1 ( and user_id = 1)

so does any feature can support it ?

gg1229505432 commented 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)

}

gg1229505432 commented 7 months ago

use this, you can add any 「where func」 you want