英文:
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)
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论