如何在 GORM 的 belongs-to 关系中构建子查询?

huangapple go评论65阅读模式
英文:

How can i build a subquery in a gorm belongs-to relationship?

问题

我正在使用Go语言中的GORM进行MySQL查询。我有以下结构体:

type Patient struct {
	gorm.Model
}

type ClinicalTrialPatient struct {
	gorm.Model
	PatientID uint
	Patient Patient
}

我想生成一个SQL语句,类似于:

SELECT * FROM `clinical_trial_patients` WHERE patient_id IN (SELECT ID FROM Patients WHERE pvs_pat_id = '1' AND DELETED_AT is null) AND `clinical_trial_patients`.`deleted_at` IS NULL

不幸的是,我不知道如何生成这样的语句。我尝试了以下代码:

result := orm.Where(&ClinicalTrialPatient{
	Patient: Patient{ 
		PvsPatId: "1",
	},
}).Find(&trialPatients)

但是生成的SQL语句如下:

SELECT * FROM `clinical_trial_patients` WHERE `clinical_trial_patients`.`deleted_at` IS NULL
英文:

I am using GORM in go for mysql queries. I have the following structs

type Patient struct {
	gorm.Model
}


type ClinicalTrialPatient struct {
	gorm.Model
	PatientID uint
	Patient Patient
}

I would like go generate a SQL Statement like

SELECT * FROM `clinical_trial_patients` WHERE patient_id IN (SELECT ID FROM Patients WHERE pvs_pat_id = '1' AND DELETED_AT is null) AND `clinical_trial_patients`.`deleted_at` IS NULL

Unfortunately I dont get it how i can generate a statement like this. I was trying something like this:

result := orm.Where(&ClinicalTrialPatient{
		Patient: Patient{ 
			PvsPatId: "1",
		},
	}).Find(&trialPatients)

But the following statement was generated

SELECT * FROM `clinical_trial_patients` WHERE `clinical_trial_patients`.`deleted_at` IS NULL

答案1

得分: 1

你可以使用Preload来处理属于关系。

type Patient struct {
    gorm.Model
    ClinicalTrialPatients []ClinicalTrialPatient // 添加这个字段
}


type ClinicalTrialPatient struct {
    gorm.Model
    PatientID uint
    Patient Patient
}

...

var result Patient

err := orm.Preload("ClinicalTrialPatients").First(&result, 1).Error
if err != nil {
    panic(err)
}

fmt.Println(result.ClinicalTrialPatients)

...

或者根据你的问题,你可以使用sub-query来实现,像这样:


    pvsPatId := "1"

    err := orm.
        Where(
            "patient_id in (?)",
            db.Table("Patients").
                Select("id").
                Where("pvs_pat_id = ?", pvsPatId),
        ).
        Find(&trialPatients).Error
    if err != nil {
        panic(err)
    }
英文:

You can use Preload to do belongs-to relationship.

type Patient struct {
    gorm.Model
    ClinicalTrialPatients []ClinicalTrialPatient // add this field
}


type ClinicalTrialPatient struct {
    gorm.Model
    PatientID uint
    Patient Patient
}

...

var result Patient

err := orm.Preload("ClinicalTrialPatients").First(&result, 1).Error
if err != nil {
	panic(err)
}

fmt.Println(result.ClinicalTrialPatients)

...

Or based on your question, you can use sub-query like this:


	pvsPatId := "1"

	err := orm.
		Where(
			"patient_id in (?)",
			db.Table("Patients").
				Select("id").
				Where("pvs_pat_id = ?", pvsPatId),
		).
		Find(&trialPatients).Error
	if err != nil {
		panic(err)
	}

huangapple
  • 本文由 发表于 2022年9月26日 17:45:28
  • 转载请务必保留本文链接:https://go.coder-hub.com/73852317.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定