Many2Many JoinTable中的自定义字段 [英] Custom fields in Many2Many JoinTable

查看:98
本文介绍了Many2Many JoinTable中的自定义字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个带有自定义JoinTable的模型:

I have this model with a custom JoinTable:

type Person struct {
  ID        int
  Name      string
  Addresses []Address `gorm:"many2many:person_addresses;"`
}

type Address struct {
  ID   uint
  Name string
}

type PersonAddress struct {
  PersonID  int
  AddressID int
  Home      bool
  CreatedAt time.Time
  DeletedAt gorm.DeletedAt
}

在创建新的 Person 时如何为 Home 字段分配值?

How is it possible to assign a value to the Home field when creating a new Person?

推荐答案

方法1

根据我在文档中看到的内容,这是您当前可能执行的一种干净方法:

Method 1

From what I can see in the docs, here's a clean way you might currently do this:

DB.SetupJoinTable(&Person{}, "Addresses", &PersonAddress{})

addr1 := Address{Name: "addr1"}
DB.Create(&addr1)

addr2 := Address{Name: "addr2"}
DB.Create(&addr2)

person := Person{Name: "jinzhu"}
DB.Create(&person)

// Add an association with default values (i.e. Home = false)
DB.Model(&person).Association("Addresses").Append(&addr1)

// Add an association with custom values
DB.Create(&PersonAddress{
    PersonID:  person.ID,
    AddressID: addr2.ID,
    Home:      true,
})

在这里,我们使用实际的联接表模型来插入具有所需值的行.

Here we're using the actual join table model to insert a row with the values we want.

我们还可以过滤关联查询:

We can also filter queries for the association:

addr := Address{}
// Query association with filters on join table
DB.Where("person_addresses.home = true").
    Model(&person).
    Association("Addresses").
    Find(&addr)

方法2

这是一种更神奇的方法,除了(code)SetupJoinTable 之外,还(ab)使用 Context 将值传递到 BeforeSave 钩子上面的代码:

Method 2

Here's a more magical way, by (ab)using the Context to pass values to a BeforeSave hook, in addition to the SetupJoinTable code from above:

func (pa *PersonAddress) BeforeSave(tx *gorm.DB) error {
    home, ok := tx.Statement.Context.Value("home").(bool)
    if ok {
        pa.Home = home
    }
    return nil
}

// ...

DB.WithContext(context.WithValue(context.Background(), "home", true)).
    Model(&person).
    Association("Addresses").
    Append(&addr2)

这种方法对我来说很棘手,但是有效.

This method feels icky to me, but it works.

这篇关于Many2Many JoinTable中的自定义字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆