7
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

GoodStaffAdvent Calendar 2017

Day 18

gormのscopesが便利

Posted at

gormのScopesが便利だったので記事にしました

UserFind()ProfileFind()Whereで同じようにID検索する処理があるとする

package main

import (
	"github.com/jinzhu/gorm"
	_ "github.com/jinzhu/gorm/dialects/postgres"
	"github.com/k0kubun/pp"
)

type User struct {
	gorm.Model
	Profile   Profile
	ProfileID int
	Email     string
}

type Profile struct {
	gorm.Model
	Name string
	Age  int
}

func main() {
	db, err := gorm.Open("postgres", "url")
	if err != nil {
		panic(err)
	}

	db.AutoMigrate(
		&User{},
		&Profile{},
	)

	user := UserFind(db, 1)
	pp.Println(user)
	profile := ProfileFind(db, 1)
	pp.Println(profile)
}

func UserFind(db *gorm.DB, id int) User {
	var user User
	db.Where("id = ?", id).Find(&user)
	return user
}

func ProfileFind(db *gorm.DB, id int) Profile {
	var profile Profile
	db.Where("id = ?", id).Find(&profile)
	return profile
}

これをScopesを使うとIDで検索する共通のメソッドが作れる

func UserFind(db *gorm.DB, id int) User {
	var user User
	db.Scopes(SearchByID(id)).Find(&user)
	return user
}

func ProfileFind(db *gorm.DB, id int) Profile {
	var profile Profile
	db.Scopes(SearchByID(id)).Find(&profile)
	return profile
}

func SearchByID(id int) func(db *gorm.DB) *gorm.DB {
	return func(db *gorm.DB) *gorm.DB {
		return db.Where("id = ?", id)
	}
}

おわりに

使いようによっては色々な使い方ができそうだなって思った。
便利!使っていこう!

7
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
7
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?