Golang Gorm one-to-many association mode Association + Find query association

Find associations


// User 拥有并属于多种 language,`user_languages` 是连接表
type User struct {
  gorm.Model
  Languages []Language `gorm:"many2many:user_languages;"`
}

type Language struct {
  gorm.Model
  Name string
}

Find all matching related records

db.Model(&user).Association("Languages").Find(&languages)

Find associations with conditions

codes := []string{"zh-CN", "en-US", "ja-JP"}
db.Model(&user).Where("code IN ?", codes).Association("Languages").Find(&languages)

db.Model(&user).Where("code IN ?", codes).Order("code desc").Association("Languages").Find(&languages)

------------------------------------------------------------------------------------------------------------------------------

 

To use the Association method, you need to query the User, and then search for the CreditCard based on the AssociationForeignKey specified in the User definition.

To query a certain piece of data, use first to query the unique value.

	u := &User{Id: 1}
	db.Debug().First(u)
	fmt.Println(u)
 
	db.Where("id=?",u.Id).First(u)
import (
	"fmt"
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
)

type User struct {
	gorm.Model
	UserName    string       `json:"username" gorm:"column:username"`
	CreditCards []CreditCard `gorm:"constraint:OnUpdate:CASCADE,OnDelete:SET NULL;"`
}

type CreditCard struct {
	gorm.Model
	Number string
	UserID int
}

func main() {
	dsn6 := "root:7PXjAkY!&nlR@tcp(192.168.11.128:3306)/test_db?charset=utf8mb4&parseTime=True&loc=Local"
	db, _ := gorm.Open(mysql.Open(dsn6), &gorm.Config{})
	db.AutoMigrate(&User{}, &CreditCard{})



    //查找 用户名为 lucas 的所有信用卡信息
	u1 := &User{UserName: "lucas"}

    //Association必须要先查出User才能关联查询对应的CreditCard
	db.First(u1)

	db.Model(u1).Association("CreditCards").Find(&u1.CreditCards)
	fmt.Println(u1)
}

Only creditcard is found here

[1.513ms] [rows:2] SELECT * FROM `credit_cards` WHERE `credit_cards`.`user_id` = 1 AND `credit_cards`.`deleted_at` IS NULL
Associate first obtains the user and then obtains the creditcard! ! ! ! ! ! ! ! !

var u User
db.Debug().Where("name = ?", "lucas").Find(&u)
fmt.Println(u)
[2.756ms] [rows:1] SELECT * FROM `user` WHERE name = 'lucas'
{1 lucas []}
//The results of the associated query are saved to the user.CreditCard property.

db.Debug().Model(&u).Association("Articles").Find(&u.Articles)
fmt.Println(u)
[0.712ms] [rows:2] SELECT * FROM `article` WHERE `article`.`user_id` = 1
{1 lucas [{1 k8s 1 {0  []}} {2 golang 1 {0  []}}]} 
	a := make([]Article, 10)
	var u User
	db.Take(&u, 3)
	db.Model(&u).Association("Articles").Find(&a)
	fmt.Println(u)
	fmt.Println(a)

{3 lucas []}
[{4 golang 3 {0  []}} {5 k8s 3 {0  []}}]

Joint table Association


Foreign key settings

Once you can accept the new model , you can talk about foreign key settings. The two structures are related to each other. The most direct idea is how do I start from one structure and then get another structure.

foreign key

If I need to use User to find out which CreditCards it owns, then what I actually do = "Query the CreditCard table with the User primary key ". 

Once we understand how foreign keys are set up, we can start to use foreign keys. Concept: Association It is a general tool used to manage all relationships. Taking the above Card&User as an example, we will manage the relationship between the above two tables. Association relationship (the above two tables are related to each other using the default foreign key/primary key method)

cs := []CreditCard{}

xiaohan := &User{
	Model:gorm.Model{
		ID:1,
	},
}
 
// 所有与xiaohan(id=1)相关联的CreditCard,找出来
d.Model(xiaohan).Association("CreditCards").Find(&cs)
 
// xiaohan数据取消与ID=1的CreditCard取消关联
d.Model(xiaohan).Association("CreditCards").Delete(&CreditCard{
	Model:gorm.Model{
		ID:1,
	},
})

The model first gets this table, and then connects to the third table of tags. After that, the most critical operation is to perform. This operation can be delete clean append.

//Add association between xiaohan and CreditCard 
d.Model(xiaohan).Association("Languages").Append(&cards)

//Cancel all associations
db.Model(xiaohan).Association("Languages").Clear()

//Object association count
db.Model(xiaohan).Association("Languages").Count()

おすすめ

転載: blog.csdn.net/qq_34556414/article/details/133143806