Symfony 4-使用where子句访问联接的表?

时间:2018-10-11 15:09:46

标签: php symfony doctrine symfony4

我有以下实体:

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;

我正在尝试执行以下操作:

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

但是这在生成SQL时不起作用:

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

基本上,在生成SQL时缺少join子句。我想念什么吗?我不确定为什么这行不通。

1 个答案:

答案 0 :(得分:0)

您可以颠倒逻辑,以获取

之类的特定员工的订单
$employee = $this->getDoctrine()->getRepository(Employee::class)->find($userId);
$orders = $employee->getOrders();

或者您可以使用查询生成器

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