在n:1关系中按可空属性排序

时间:2011-10-04 14:38:06

标签: sorting grails groovy

我有以下问题 - 只给出整个域环境的片段,我会尝试解释它:

我有这两个领域类,想要获得一份研究清单,并按照他们(当前)医生的名义对它们进行排序。我的问题是,我不知道如何使用gorm进行标准查询...

class Study {    
    Date studydate
    String comment
    static belongsTo = [currentPatient:Patient, originalPatient: Patient, originalPhysician: Physician, currentPhysician: Physician]

    static mapping = {
        columns{
            currentPatient column:'id_patient_current'
            originalPatient column:'id_patient'
            originalPhysician column:'id_physician'
            currentPhysician column:'id_physician_current'
        }
    }
}

class Physician {
    String personname

    static hasMany = [currentStudies: Study, originalStudies: Study]

    static mappedBy = [currentStudies:  'currentPhysician',
                       originalStudies: 'originalPhysician']
}

现在查询:

def physician = Physician.get(params?.phId)

def studies = Study.withCriteria{
    and{
        maxResults(limit as Integer)
        firstResult(offset as Integer)

        currentPhysician{
            if(physician){
                eq('id', physician.id)
            }    
            order('personname', 'asc')
        }
    }
}

问题是并非每项研究都必须有医生 - 有可能,列(在数据库中) - “id_physician”和“id_physician_current” - 包含NULL值(患者不是来自医生)。

通过直接sql查询没问题:

select st.id, ph.personname  from study as st left join Physician as ph on ph.ID = st.ID_Physician_Current order by ph.PersonName

我在mssql数据库上使用grails 1.3.7

1 个答案:

答案 0 :(得分:0)

我相信以下查询可以满足您的要求。

def studies = Study.withCriteria{
    maxResults(limit as Integer)
    firstResult(offset as Integer)
    order('currentPhysician.personname', 'asc')

    if(physician) {
        or {
            eq('currentPhysician', physician)
            isNull('currentPhysician')
        }
    }

    order('currentPhysician.personname', 'asc')
}

也许不是你想象的完全相同的sql,但是如果你担心你不应该写标准。