Go语言 加载空值左联接数据

hc8w905p  于 2023-04-09  发布在  Go
关注(0)|答案(2)|浏览(122)

我试图用IndustryOrganization左连接,我需要选择Organization,其中包含所有Map的Industry,以及未Map的Industry

type Industry struct {
    gorm.Model
    Name string `gorm:"type:varchar(255);column:name;not null;unique"`
}

type Organization struct {
    gorm.Model
    Name string `gorm:"type:varchar(255);column:name;not null"`
}

type IndustryForOrganization struct {
    gorm.Model
    IndustryId     uint `gorm:"column:industryId;not null;"`
    OrganizationId uint `gorm:"column:organizationId;not null"`

    Organization organization.Organization `gorm:"foreignkey:organizationId;constraint:OnUpdate:CASCADE,OnDelete:CASCADE;"`
    Industry     industry.Industry         `gorm:"foreignkey:industryId;constraint:OnUpdate:CASCADE,OnDelete:CASCADE;"`
}

行业动态
| 身份证|名称|
| --------------|--------------|
| 1|软件|
| 二|BPO|
| 三|教育|
| 四|食品和加工|
| 五|汽车|
行业组织
| 身份证|组织ID|行业ID|
| --------------|--------------|--------------|
| 1|1|1|
| 二|1|三|
| 三|1|五|
| 四|二|二|
我需要为组织ID 1生成以下输出。
| 组织ID|行业ID|行业名称|
| --------------|--------------|--------------|
| 1|1|软件|
| 零|二|BPO|
| 1|三|教育|
| 零|四|食品和加工|
| 1|五|汽车|
我有一个查询来获取所需的输出

SELECT industries.id, industries.name, industryForOrganization.organizationId  
 FROM  industries 
 LEFT JOIN industryForOrganization ON industries.id = industryForOrganization.industryId 
 AND industryForOrganization.organizationId = 1

但我想实现相同的使用gorm.我试图实现与下面提到的代码,但我可以得到预期的输出.我没有得到任何值为IndustryForOrganizationIndustry

var industryForOrganization []*IndustryForOrganization
    err := r.db.Debug().
        Raw("SELECT industries.*, industryForOrganization.* FROM  industries LEFT JOIN industryForOrganization ON industries.id = industryForOrganization.industryId AND industryForOrganization.organizationId = ? ", organisationId).
        Scan(&industryForOrganization).Error

由于我是刚接触golang的,所以解决起来并不困难,请大家多多指导,先谢了。

gwo2fgha

gwo2fgha1#

下面的代码将完全满足您的需要:

var industryForOrganization []*IndustryForOrganization

err := db.Table("industries")
.Select("industries.*, industryForOrganization.*")
.Joins("left join industryForOrganization on industries.id = industryForOrganization.industryId AND industryForOrganization.organizationId = ?", organisationId)
.Scan(&industryForOrganization).Error
jv4diomz

jv4diomz2#

从前面的答案中接收到零值,因为这是您尝试填充的“IndustryForOrganization”模型的默认值。
调整模型以使用可以为空的指针将解决这个问题。

type IndustryForOrganization struct {
    gorm.Model
    IndustryId     *uint `gorm:"column:industryId"`
    OrganizationId *uint `gorm:"column:organizationId"`

    Organization *organization.Organization `gorm:"foreignkey:organizationId;constraint:OnUpdate:CASCADE,OnDelete:CASCADE;"`
    Industry     *industry.Industry         `gorm:"foreignkey:industryId;constraint:OnUpdate:CASCADE,OnDelete:CASCADE;"`
}`

相关问题