golang gorm 搜索sql组装

gorm例子

func (r *repo) List(offset, pageSize int, filter *do.Filter) (total int, list []do.UserDo, err error) {
	rows := make([]models.User, 0)
	params := make([]interface{}, 0)
	condition := " u.state = ? and u.is_quit = 0 "
	params = append(params, do.UserStateOk)
	if filter.Name != "" {
		condition += " and u.user_name like ? "
		params = append(params, "%"+filter.Name+"%")
	}

	if filter.DateStart != "" {
		condition += " and u.login_at >= ? "
		params = append(params, filter.DateStart)
	}

	if filter.DateEnd != "" {
		condition += " and u.login_at <= ? "
		params = append(params, filter.DateEnd)
	}

	err = GetDB().Table("users u").
		Where(condition, params...).
		Count(&total).
		Limit(pageSize).Offset(offset).Order("u.id desc").Find(&rows).Error
	if err != nil {
		return
	}

	util.DeepCopy(rows, &list)

	return
}

你可能感兴趣的:(gorm,sql,golang)