使用Doctrine Query Builder编写查询

时间:2015-02-23 13:47:46

标签: symfony doctrine-orm query-builder

我有三个表患者,症状,患者症状

patient    Symptoms     PatientSymptoms
id name    id,name      pid,sid

我可以使用sql编写查询

SELECT Distinct(p.id) FROM Patient p join PatientSymptoms on p.id = PatientSymptoms.patient_id join Symptoms s on   PatientSymptoms.symptom_id  = symptoms.id;

我尝试使用查询构建器

       $repo=$em->getRepository("EntityBundle:Patient");
         $query = $repo->createQueryBuilder('d');
     $query->leftjoin('d.patientSymptoms', 'r')
          ->where('r.symptoms =:name')->setParameter('id', $id);

但是没有希望得到帮助.....

我的病人orm.yml

 oneToMany:
        symptoms:
            targetEntity: Symptoms
            mappedBy: symptom

PatientSymptoms.orm.yml
manyToOne:
    patient:
        targetEntity: Patient
        inversedBy: symptoms
        joinColumn:
            name: patient_id
            referencedColumnName: id
    symptom:
        targetEntity: Symptoms
        inversedBy: patients
        joinColumn:
            name: symptom_id
            referencedColumnName: id

Symptoms.orm.yml

 oneToMany:
        patients:
            targetEntity: Patient
            mappedBy: patient

1 个答案:

答案 0 :(得分:1)

请尝试以下代码:

$result = $em->getRepository('EntityBundle:Patient')
    ->createQueryBuilder('p')
    ->select('DISTINCT(p.id)')
    ->innerJoin('p.PatientSymptoms','ps')
    ->innerJoin('ps.Symptoms', 's')
    ->andWhere('s.symptoms = :name')
    ->setParameter('name', $name)
    ->getArrayResult();

假设您的实体关系设置正确

,这将有效