一对一查询
最后更新于:2022-04-02 02:48:33
[TOC]
## 一对一情况关联表
如:
```
场景一 :
[user] id name user_data_id
[user_data] id address
场景一:
[user] id name
[user_data] id address user_id
```
> 注意: 创建`struct` 时 把有对方 `user_id `的表 为 `rel(one)`
### 针对场景一的操作
```go
//==========表==========
[user] id name profile_id
[profile] id age
//==========表==========
// ========== 结构体==========
type User struct {
Id int
Name string
Profile *Profile `orm:"rel(one)"` // OneToOne relation
}
type Profile struct {
Id int
Age int16
User *User `orm:"reverse(one)"` // 设置一对一反向关系(可选)
}
// ========== 结构体==========
//==========已经取得了 User 对象,查询 Profile==========
user := &User{Id: 1}
o.Read(user)
if user.Profile != nil {
o.Read(user.Profile)
}
//==========直接关联查询==========
user := &User{}
o.QueryTable("user").Filter("Id", 1).RelatedSel().One(user)
// 自动查询到 Profile
fmt.Println(user.Profile)
//可正常取值
fmt.Println(user.Profile.User)
//==========通过 User 反向查询 Profile==========
var profile Profile
err := o.QueryTable("profile").Filter("User__Id", 1).One(&profile)
if err == nil {
fmt.Println(profile)
}
```
### 针对场景二的操作
```go
type HsUser struct {
UserId int `orm:"pk"`
UserLogin string
UserName string
UserSex int
HsUserConfig *HsUserConfig `orm:"reverse(one)"`
}
type HsUserConfig struct {
CfgId string `orm:"pk;"`
UserId int `orm:"-"` //注意不需要此字段,
CfgDataType string
HsUser *HsUser `orm:"null;rel(one);on_delete(set_null);column(user_id)"`
}
```
#### 增
```
o := orm.NewOrm()
//需要先添加关联表,获得user_id
user := new(HsUser)
user.UserId = 9991
user.UserName = "999test1"
i, e := o.Insert(user)
ThrowErr(e)
fmt.Println(i)
userConfig := new(HsUserConfig)
```
```
//把携带user_id 表发送给userConfig
userConfig.HsUser = user
userConfig.CfgId = "hello"
i2, e2 := o.Insert(userConfig)
ThrowErr(e2)
fmt.Println(i2)
fmt.Println(userConfig)
```
#### 改
```
userConfig := new(HsUserConfig)
//查
o.QueryTable(userConfig).Filter("user_id", 107).RelatedSel().One(userConfig)
o.Read(userConfig.HsUser)
//更新 userconfig 表
userConfig.CfgDataType = "CfgDataType"
i, i2 := o.Update(userConfig)
//更新 user 表
userConfig.HsUser.UserLogin = "UserLogin"
i4, i3 := o.Update(userConfig.HsUser)
```
#### 查
```
o := orm.NewOrm()
userConfig := new(HsUserConfig)
o.QueryTable(userConfig).Filter("user_id", 107).One(userConfig)
o.Read(userConfig.HsUser)
//o.QueryTable(userConfig).Filter("user_id", 107).RelatedSel().One(userConfig) 能直接取值 userConfig.HsUser 的值,但无法转json
//转json
bytes, e := json.Marshal(userConfig)
ThrowErr(e)
fmt.Println("json:", string(bytes)) //{"CfgId":"2A442CC4-65AF-485F-A530-B034C4C8B34F","UserId":0,"CfgDataType":"contact","HsUser":{"UserId":107,"UserLogin":"检验总指挥","UserName":"检验总指挥","UserSex":0,"HsUserConfig":null}}
```
> 注意: 在`user` 表的strcut 表中 无需声明`profile_id` 关联表时就指定,可自定义
`Profile *Profile `orm:"rel(one);column(profile_id)"`
';