简体   繁体   English

如何使用Join和where子句从多个表中获取数据

[英]How to fetch data from multiple tables using Join and where clause

I have written a simple symfony controller where I have two table known as specialtyarea and physician. 我写了一个简单的symfony控制器,我有两个表称为specialarea和doctor。

this is the basic structure of the table 这是表格的基本结构

specialtyarea
-----------------
id | name       |
-----------------
1  | dentist    |
2  | physician  |

Physician table is related to specialtyarea as shown: 医生表是关系到specialtyarea如图所示:

Physician
--------------------
id | name | specfk |
--------------------
1  | John  | 1     |
2  | Doe   | 2     |
3  | Ann   | 2     |

I am trying to fetch all the physician where specialty area is 2 我正在尝试取得专业领域为2的所有医生

This is my snippet of code 这是我的代码片段

public function getAllPhysicianAction($specId)
{
     $id = $this->getDoctrine()->getRepository('Bundle:SpecArea')
        ->find($specId); //assuming that this returns all the id from the specialty table

    $allPhysician = $id->getPhysician()->...   //kind of lost here    
}

How can I retrieve all the records from the physician table using the specialty Id? 如何使用专业ID从医师表中检索所有记录?

Use the findBy() method of the "physician" repository: 使用“physician”存储库的findBy()方法:

(You didn't post your actual entities so I'm guessing the field/entity names.) (你没有发布你的实际实体,所以我猜测字段/实体名称。)

$spec = $this->getDoctrine()->getRepository('Bundle:SpecArea')->find($specId); 

$physicians = $this->getDoctrine()->getRepository('Bundle:Physician')->findBy(['spec' => $spec]);

You can also use $specId ID directly instead of fetching the entire entity from database: 您也可以直接使用$specId ID,而不是从数据库中获取整个实体:

    $physicians = $this->getDoctrine()->getRepository('Bundle:Physician')->findBy(['spec' => $specId]);

See: Working with Objects - Querying - By Simple Conditions 请参阅: 使用对象 - 查询 - 按简单条件

I believe that you can just call findBy on your physician repository. 我相信你可以在你的医生库中调用findBy。

/**
 * @Route("/physicians/{specId}", name="getAllPhysician")
 */
public function getAllPhysicianAction($specId)
{
    $allPhysician = $this->getDoctrine()
    //call the repository of your physician table
    ->getRepository('Bundle:physician')
    ->findBy(['specfk' => $specId]);

    var_dump($allPhysician);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM