简体   繁体   中英

Symfony 4 - Accessing joined tables with where clause?

I have the following entity:

class Orders
{
  ...
      /**
      * One Order has Many Employees.
      * @ORM\ManyToMany(targetEntity="Employee")
      * @ORM\JoinTable(name="orders_employees",
      *      joinColumns={@ORM\JoinColumn(name="order_id", referencedColumnName="id")},
      *      inverseJoinColumns={@ORM\JoinColumn(name="employee_id", referencedColumnName="id")},
      *      )
      */
      private $employees;

I'm trying to do the following:

   $orders = $this->getDoctrine()->
        ->getRepository(Orders::class)
        ->findBy(['employees' => $userId);

however this doesn't work as it's generating the SQL:

... FROM orders t0 WHERE orders_employees.employee_id = ?

Basically it's missing the join clause when it generates the SQL. Am I missing something? I'm not sure why this isn't working.

You could reverse your logic to get orders for a particular employee like

$employee = $this->getDoctrine()->getRepository(Employee::class)->find($userId);
$orders = $employee->getOrders();

Or you could use query builder

$repo = $this->getDoctrine()->getRepository(Orders::class);
$orders= $repo->createQueryBuilder('o')
                ->select('o')
                ->join('o.employees' ,'e')
                ->where('e.id = :id')
                ->setParameter('id',$userId)
                ->getResult();

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