当前位置: 首页>>代码示例>>Golang>>正文


Golang DB.Where方法代码示例

本文整理汇总了Golang中github.com/jinzhu/gorm.DB.Where方法的典型用法代码示例。如果您正苦于以下问题:Golang DB.Where方法的具体用法?Golang DB.Where怎么用?Golang DB.Where使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在github.com/jinzhu/gorm.DB的用法示例。


在下文中一共展示了DB.Where方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。

示例1: ChangePassword

func ChangePassword(username string, newpassword string, db *gorm.DB) (int, error) {
	var user User
	var err error

	dbErr := db.Where(&User{UserName: username}).Find(&user).Error
	if dbErr != nil {
		if dbErr == gorm.RecordNotFound {
			WARNING.Println(UnregisteredUser.Error() + " ,username: " + username)
			return 401, UnregisteredUser
		} else {
			ERROR.Println(dbErr.Error())
			return 500, DatabaseError
		}
	}

	user.Password, err = EncryptPassword(newpassword)
	if err != nil {
		ERROR.Println(err.Error())
		return 500, EncryptionError
	}

	db.Save(&user)
	updatePasswordErr := UpdatePasswordRecordLoginCount(user.Id, false, db)

	if updatePasswordErr != nil {
		ERROR.Println("Password record not updated for userId: " + strconv.FormatInt(user.Id, 10) + ", Error details: " + updatePasswordErr.Error())
		return 500, DatabaseError
	}

	db.Save(&ActivityLog{UserId: user.Id, TokenId: -1, ActivityTime: time.Now().UTC(), Event: PASSWORD_CHANGE})
	TRACE.Println("Password changed for userId: " + strconv.FormatInt(user.Id, 10))

	return 200, nil
}
开发者ID:RodrigoDev,项目名称:gondalf,代码行数:34,代码来源:handlerUtils.go

示例2: ValidateSessionToken

func ValidateSessionToken(sessionToken string, db *gorm.DB) (error, int64) {
	var token Token

	dbErr := db.Where(&Token{Token: sessionToken}).Find(&token).Error
	if dbErr != nil {
		if dbErr == gorm.RecordNotFound {
			WARNING.Println(InvalidSessionToken.Error() + ", sessionToken: " + sessionToken)
			return InvalidSessionToken, -1
		}
		ERROR.Println(dbErr.Error() + ", sessionToken: " + sessionToken)
		return dbErr, -1
	}

	if token.Active && token.ExpiresAt.After(time.Now().UTC()) {
		TRACE.Println("SessionToken validated: " + sessionToken)
		timeLeft := token.ExpiresAt.Sub(time.Now().UTC())
		if timeLeft.Minutes() < 5 {
			token.ExpiresAt = token.ExpiresAt.Add(time.Duration(GetTimeExtension()) * time.Minute)
		}
		token.LastAccessedAt = time.Now().UTC()
		db.Save(&token)
		return nil, token.UserId
	}

	return ExpiredSessionToken, -1
}
开发者ID:RodrigoDev,项目名称:gondalf,代码行数:26,代码来源:handlerUtils.go

示例3: Retreive

// Retreive purchase from database
func (purch *Purchase) Retreive(db *gorm.DB) ([]Purchase, error) {
	var purchs []Purchase
	err := db.Where(purch).Find(&purchs).Error
	if err != nil {
		return nil, err
	}

	for i, p := range purchs {
		order := Order{}
		order.ID = p.OrderId

		if err := db.Model(&p).Related(&order, "OrderId").Error; err != nil {
			return nil, err
		}

		pproducts := []PurchaseProduct{}
		if err := db.Model(order).Related(&pproducts, "Pproducts").Error; err != nil {
			fmt.Println("[ERROR] ", err.Error())
			return nil, err
		}
		order.Pproducts = pproducts

		p.PurschaseOrder = order
		purchs[i] = p
	}

	return purchs, err
}
开发者ID:asvins,项目名称:warehouse,代码行数:29,代码来源:purchase.go

示例4: GetUser

/*
GetUser returns the user with that id
*/
func GetUser(db *gorm.DB, id int) (*User, error) {
	var user User
	if err := db.Where("ID = ?", id).First(&user).Error; err != nil {
		return nil, err
	}
	return &user, nil
}
开发者ID:IIC2173-2015-2-Grupo2,项目名称:news-api,代码行数:10,代码来源:user.go

示例5: CreateNewTokenDbEntry

//Create new token entry in the database
func CreateNewTokenDbEntry(login LoginCredential, db *gorm.DB) (string, error) {
	user := User{}
	db.Where(&User{UserName: login.Username}).Find(&user)

	token := Token{}
	token.UserId = user.Id
	token.Key = uuid.New()
	token.CreatedAt = time.Now().UTC()
	token.LastAccessedAt = time.Now().UTC()
	token.Token = generateSessionToken(login.Username+token.CreatedAt.String(), token.Key)
	token.Active = true
	expiryTime, err := GetTimeOutValue(login.DeviceId)
	if err != nil {
		ERROR.Println(err.Error())
		return "", err
	}

	token.ExpiresAt = expiryTime

	var device DeviceType
	db.Where(&DeviceType{DeviceCode: login.DeviceId}).Find(&device)

	token.DeviceTypeId = device.Id

	db.Save(&token)

	db.Save(&ActivityLog{UserId: token.UserId, TokenId: token.Id, ActivityTime: time.Now().UTC(), Event: LOGIN})

	return token.Token, nil
}
开发者ID:RodrigoDev,项目名称:gondalf,代码行数:31,代码来源:handlerUtils.go

示例6: CreateClient

func CreateClient(db gorm.DB, options *Options) (id int64) {

	var c Client

	db.Where(
		&Client{
			Hostname:  options.Hostname,
			Interface: options.Interface,
			MacAddr:   options.InterfaceData.HardwareAddr.String(),
			Ip:        options.Ip,
		},
	).First(&c)

	if c.Id != 0 {
		db.Model(&c).Update(
			&Client{
				LastSeen: time.Now().Unix(),
			},
		)
	} else {
		c.LastSeen = time.Now().Unix()
		c.Hostname = options.Hostname
		c.MacAddr = options.InterfaceData.HardwareAddr.String()
		c.Interface = options.Interface
		c.Ip = options.Ip

		db.Table("clients").Create(&c)
	}

	options.Client = &c

	return c.Id
}
开发者ID:mehulsbhatt,项目名称:dnas,代码行数:33,代码来源:output.go

示例7: checkVideoID

func checkVideoID(db *gorm.DB, videos []*putube.YoutubeVideo) (newVideoIdxs []int) {

	videoIDs := make([]string, len(videos))
	for i := range videos {
		videoIDs[i] = videos[i].VideoID
	}

	var existingVideos []putube.YoutubeVideo

	if db.Where("video_id in (?)", videoIDs).Find(&existingVideos).RecordNotFound() {
		existingVideos = []putube.YoutubeVideo{}
	}

	newVideoIdxs = []int{}
	for i := range videos {
		nf := true
		for j := range existingVideos {
			if videos[i].VideoID == existingVideos[j].VideoID {
				nf = false
				break
			}
		}
		if nf {
			newVideoIdxs = append(newVideoIdxs, i)
		}
	}

	return
}
开发者ID:rooa,项目名称:puku,代码行数:29,代码来源:save.go

示例8: GetByEmail

func (p *AuthDao) GetByEmail(db *gorm.DB, email string) *User {
	var user User
	if db.Where("email = ? AND provider = ?", email, "email").First(&user).RecordNotFound() {
		return nil
	}
	return &user
}
开发者ID:itpkg,项目名称:base,代码行数:7,代码来源:dao.go

示例9: FeedForGroupGet

func FeedForGroupGet(db gorm.DB, params martini.Params, res http.ResponseWriter) (int, string) {
	podcast := models.Group{}
	var media = []models.Media{}
	if err := db.Where(&models.Group{Slug: params["slug"]}).First(&podcast).Error; err != nil {
		res.Header().Set(ContentType, PlainType)
		return http.StatusNotFound, "Feed not found"
	}
	db.Model(&podcast).Order("created_at desc").Limit(15).Related(&media)

	tpl, err := template.New("xml_feed").Funcs(template.FuncMap{"short": ShortenString}).Parse(xml_feed_t)
	if err != nil {
		res.Header().Set(ContentType, PlainType)
		return http.StatusInternalServerError, "Generating XML failed"
	}
	data := Feed{&podcast, &media}
	buf := new(bytes.Buffer)
	err = tpl.Execute(buf, data)
	log.Println(err)
	if err != nil {
		res.Header().Set(ContentType, PlainType)
		return http.StatusInternalServerError, "Generating XML failed"
	}
	res.Header().Set(ContentType, RSSType)
	return http.StatusOK, buf.String()
}
开发者ID:RadioTerminal,项目名称:podcaster,代码行数:25,代码来源:feed.go

示例10: Bootstrap

// Bootstrap creates "migrations" table
// to keep track of already run database migrations
func Bootstrap(db *gorm.DB) error {
	migrationName := "bootstrap_migrations"

	migration := new(Migration)
	// Using Error instead of RecordNotFound because we want to check
	// if the migrations table exists. This is different from later migrations
	// where we query the already create migrations table.
	exists := nil == db.Where("name = ?", migrationName).First(migration).Error

	if exists {
		logger.Infof("Skipping %s migration", migrationName)
		return nil
	}

	logger.Infof("Running %s migration", migrationName)

	// Create migrations table
	if err := db.CreateTable(new(Migration)).Error; err != nil {
		return fmt.Errorf("Error creating migrations table: %s", db.Error)
	}

	// Save a record to migrations table,
	// so we don't rerun this migration again
	migration.Name = migrationName
	if err := db.Create(migration).Error; err != nil {
		return fmt.Errorf("Error saving record to migrations table: %s", err)
	}

	return nil
}
开发者ID:RichardKnop,项目名称:example-api,代码行数:32,代码来源:bootstrap.go

示例11: main

func main() {
	var (
		db gorm.DB
	)

	db = SetupDb()

	db.Save(&User{
		FirstName: "John",
		LastName:  "Doe",
		Age:       24,
	})

	db.Save(&User{
		FirstName: "Jane",
		LastName:  "Doe",
		Age:       52,
	})
	db.Save(&User{
		FirstName: "Joe",
		LastName:  "Shmoe",
		Age:       10,
	})

	//START CODE OMIT
	var users []User
	db.Where("last_name = ?", "Doe").Or("age < ?", 12).Limit(2).Order("age", true).Find(&users)
	for _, user := range users {
		fmt.Printf("%+v,", user)
	}
	fmt.Println()
	//END CODE OMIT
}
开发者ID:GoSteelProgrammers,项目名称:talk-review-orms,代码行数:33,代码来源:query.go

示例12: BeforeSave

// BeforeSave invokes required actions before persisting.
func (u *User) BeforeSave(db *gorm.DB) (err error) {
	if u.Slug == "" {
		for i := 0; true; i++ {
			if i == 0 {
				u.Slug = slugify.Slugify(u.Username)
			} else {
				u.Slug = slugify.Slugify(
					fmt.Sprintf("%s-%d", u.Username, i),
				)
			}

			notFound := db.Where(
				"slug = ?",
				u.Slug,
			).Not(
				"id",
				u.ID,
			).First(
				&User{},
			).RecordNotFound()

			if notFound {
				break
			}
		}
	}

	if u.Email != "" {
		email, err := govalidator.NormalizeEmail(
			u.Email,
		)

		if err != nil {
			return fmt.Errorf("Failed to normalize email")
		}

		u.Email = email
	}

	if u.Password != "" {
		encrypt, err := bcrypt.GenerateFromPassword(
			[]byte(u.Password),
			bcrypt.DefaultCost,
		)

		if err != nil {
			return fmt.Errorf("Failed to encrypt password")
		}

		u.Hashword = string(encrypt)
	}

	if u.Hash == "" {
		u.Hash = base32.StdEncoding.EncodeToString(
			securecookie.GenerateRandomKey(32),
		)
	}

	return nil
}
开发者ID:umschlag,项目名称:umschlag-api,代码行数:61,代码来源:user.go

示例13: BeforeSave

// BeforeSave invokes required actions before persisting.
func (u *Team) BeforeSave(db *gorm.DB) (err error) {
	if u.Slug == "" {
		for i := 0; true; i++ {
			if i == 0 {
				u.Slug = slugify.Slugify(u.Name)
			} else {
				u.Slug = slugify.Slugify(
					fmt.Sprintf("%s-%d", u.Name, i),
				)
			}

			notFound := db.Where(
				"slug = ?",
				u.Slug,
			).Not(
				"id",
				u.ID,
			).First(
				&Team{},
			).RecordNotFound()

			if notFound {
				break
			}
		}
	}

	return nil
}
开发者ID:umschlag,项目名称:umschlag-api,代码行数:30,代码来源:team.go

示例14: getUserById

func getUserById(db *gorm.DB, uId int64) (*MaillistUser, error) {
	var mu MaillistUser
	err := db.Where(&MaillistUser{UserId: uId}).Find(&mu).Error
	if err != nil {
		return nil, err
	}
	return &mu, nil
}
开发者ID:slnaing07,项目名称:revel-modz,代码行数:8,代码来源:maillist_user.go

示例15: getUserDetailByUserId

func getUserDetailByUserId(db *gorm.DB, userid int64) (*UserDetail, error) {
	var user UserDetail
	err := db.Where(&UserDetail{UserId: userid}).First(&user).Error
	if err != nil {
		return nil, err
	}
	return &user, nil
}
开发者ID:jwmiller19,项目名称:revel-modz,代码行数:8,代码来源:userdetail.go


注:本文中的github.com/jinzhu/gorm.DB.Where方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。