Php 使用findAll获取过滤的关联对象
我在互联网上搜索过,但没有找到这个问题的确切答案。 我拥有以下实体:Php 使用findAll获取过滤的关联对象,php,sql,symfony,doctrine,Php,Sql,Symfony,Doctrine,我在互联网上搜索过,但没有找到这个问题的确切答案。 我拥有以下实体: /** * @ORM\Entity * @ORM\Table(name="category") */ class Category { /* * ... */ /** * @ORM\OneToMany(targetEntity="Product", mappedBy="category") */ protected $products; public
/**
* @ORM\Entity
* @ORM\Table(name="category")
*/
class Category
{
/*
* ...
*/
/**
* @ORM\OneToMany(targetEntity="Product", mappedBy="category")
*/
protected $products;
public function __construct()
{
$this->products = new ArrayCollection();
}
/**
* Add product
*
* @param \AppBundle\Entity\Product $product
*
* @return Category
*/
public function addProduct(\AppBundle\Entity\Product $product)
{
$this->products[] = $product;
return $this;
}
/**
* Remove product
*
* @param \AppBundle\Entity\Product $product
*/
public function removeProduct(\AppBundle\Entity\Product $product)
{
$this->products->removeElement($product);
}
/**
* Get products
*
* @return \Doctrine\Common\Collections\Collection
*/
public function getProducts()
{
return $this->products;
}
}
/**
* @ORM\Entity
* @ORM\Table(name="product")
*/
class Product
{
/*
* ...
*/
/**
* @ORM\ManyToOne(targetEntity="Category", inversedBy="products")
* @ORM\JoinColumn(name="category_id", referencedColumnName="id")
*/
protected $category;
/**
* @ORM\Column(type="boolean")
*/
protected $active;
/**
* Set category
*
* @param \AppBundle\Entity\Category $category
*
* @return Product
*/
public function setCategory(\AppBundle\Entity\Category $category = null)
{
$this->category = $category;
return $this;
}
/**
* Get category
*
* @return \AppBundle\Entity\Category
*/
public function getCategory()
{
return $this->category;
}
/**
* Set active
*
* @param boolean $active
*
* @return Product
*/
public function setActive($active)
{
$this->active= $active;
return $this;
}
/**
* Get active
*
* @return boolean
*/
public function getActive()
{
return $this->active;
}
}
我只想这样做:
$em = $this->getDoctrine()->getManager();
$categories = $em->getRepository('AppBundle\Entity\Category')->findAll();
$json = $serializer->serialize($categories, 'json');
在json结果中,我希望确保所有类别都有其关联的产品通过status=true进行过滤。换句话说,我希望在前端以类别对象数组的形式获得结果,每个类别都有一个活动的产品数组只有
我知道在Django可以做得很简单
这可以在理论上实现吗?如果是,如何实现。
请直截了当地回答
我用过的解决方案
将方法添加到您的实体中,如下所示:我已经看到了答案,这不是我想要的。该解决方案假设我要筛选特定类别的产品。我想要的是将所有类别作为一个数组,每个类别对象都有一个仅活动的产品数组。因此,使用查询生成器使repository method
findAllWithProducts
获取带有产品的所有类别。这将实现thanx,但棘手的部分是使用LEFT JOIN来获取没有产品的类别对象。向实体添加方法如下:我已经看到了答案,这不是我想要的。抱歉。该解决方案假设我要筛选特定类别的产品。我想要的是将所有类别作为一个数组,每个类别对象都有一个仅活动的产品数组。因此,使用查询生成器使repository methodfindAllWithProducts
获取带有产品的所有类别。这将实现thanx,但棘手的部分是使用LEFT JOIN来获取没有产品的类别对象。
$qb = $em->createQueryBuilder()
->select('c')
->from('AppBundle:Category','c')
->leftJoin('c.products','p','WITH','p.status = :status')
->addSelect('p')
->setParameter('status', true);