简体   繁体   中英

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.

this is the basic structure of the table

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

Physician table is related to specialtyarea as shown:

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

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?

Use the findBy() method of the "physician" repository:

(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:

    $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.

/**
 * @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);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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