I' searched all over the Internet but I've not found a definite answer to this question. I have the following entities:
/**
* @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;
}
}
I only want to do this:
$em = $this->getDoctrine()->getManager();
$categories = $em->getRepository('AppBundle\Entity\Category')->findAll();
$json = $serializer->serialize($categories, 'json');
and in the json result I want to make sure that all categories have their associated products filtered by status=true.In other words I want to get the results in the front end as an array of category objects with each category having an array of products that are active only.
I know it can be done trivially in Django.
Can it be done in doctrine?If yes how. Strait answers please.
SOLUTION I'VE USED
$qb = $em->createQueryBuilder()
->select('c')
->from('AppBundle:Category','c')
->leftJoin('c.products','p','WITH','p.status = :status')
->addSelect('p')
->setParameter('status', true);