Symfony2 ManyToOne重复

时间:2016-01-02 02:02:44

标签: symfony one-to-many many-to-one where-in

我有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;
 }
}

ServiceRepository

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

1 个答案:

答案 0 :(得分:1)

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

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

    return $query->getResult();
}

您可以使用查询构建器的流体接口实现相同的功能。但是,当查询本身不是基于用户输入在运行时构建时,这不会添加任何值。