Symfony2 ManyToOne 重复

Symfony2 ManyToOne duplicated

我有 2 个实体。我想得到如下结果。我在我的服务器上试过这个:

"SELECT s.se_name, c.ca_name FROM service s inner join category c ON s.ca_id_id = c.id"

一切正常。但现在我想将其转换为 Symfony 查询。没有 WHERE 我得到了所有的组合。在这种情况下如何使用 WHERE?

+----+---------+         +----+---------+-------+
+ id + ca_name +         + id + se_name + ca_id +
+----+---------+         +----+---------+-------+        
+ 1  + A       +    +    + 1  + a1      + 1     +  =>  a1 .. A
+----+---------+         +----+---------+-------+      a2 .. A
+ 2  + B       +         + 2  + a2      + 1     +
+----+---------+         +----+---------+-------+

服务实体:

/**
* Service
*
* @ORM\Table(name="service")
* @ORM\Entity(repositoryClass="AppBundle\Repository\ServiceRepository")
*/
class Service {
 ...

 /**
 * @ORM\ManyToOne(targetEntity="Category", inversedBy="services", cascade={"persist","remove"})
 * @ORM\JoinColumn(onDelete="CASCADE")
 */
 private $caId;

 /**
 * Set caId
 *
 * @param \AppBundle\Entity\Category $caId
 *
 * @return Service
 */
 public function setCaId(\AppBundle\Entity\Category $caId = null)
 {
     $this->caId = $caId;
     return $this;
 }

 /**
 * Get caId
 *
 * @return \AppBundle\Entity\Category
 */
 public function getCaId()
 {
     return $this->caId;
 }
}

类别实体:

/**
* Category
*
* @ORM\Table(name="category")
* @ORM\Entity(repositoryClass="AppBundle\Repository\CategoryRepository")
*/
class Category {
 ...

 /**
 * @ORM\OneToMany(
 *   targetEntity="Service",
 *   mappedBy="caId"
 * )
 */
 private $services;

 /**
 * Constructor
 */
 public function __construct()
 {
   $this->services = new ArrayCollection();
 }

 /**
 * Get orders
 *
 * @return Collection
 */
 public function getServices()
 {
   return $this->services;
 }
}

服务库

   /**
   * @return \Doctrine\Common\Collections\ArrayCollection
   */
  public function getAllServices()
  {
    $qb = $this
        ->createQueryBuilder('s')
        ->select('c.caName, s.id, s.seName, s.sePrice')
        ->from('AppBundle:Category', 'c');
    return $qb->getQuery()->getResult();
  }

你也可以在 Doctrine 的查询语言中使用连接。在您的存储库中,您可以执行以下操作:

public function getAllServices()
{
    $query = $this->getEntityManager()->createQuery(
        'SELECT service
        FROM AppBundleService AS service
        INNER JOIN service.caId'
    );

    return $query->getResult();
}

您可以使用查询生成器的流畅界面实现同样的效果。但是,当查询本身不是在运行时基于用户输入构建的时,这不会增加任何价值。