I have a query that looks for results obtained from a variable in the controller.
$category = $request->request->get('category');
$catContent = $em->getRepository('PublicartelAppBundle:Content')->findByCategory($category);
public function findByCategory($category)
{
$em = $this->getEntityManager();
$dql = 'SELECT c FROM Publicartel\AppBundle\Entity\Content c';
if (!is_null($category)) {
$dql .= " WHERE c.categories.name = category";
}
$query = $this->getEntityManager()
->createQuery($dql)
->setHydrationMode(\Doctrine\ORM\Query::HYDRATE_ARRAY);
if (!is_null($category)) {
$query->setParameter('category', $category);
}
return $query->getResult();
}
But when I run the action for the query I get this error occurs:
[Syntax Error] line 0, col 71: Error: Expected =, <, <=, <>, >, >=, !=, got '.'
SELECT c FROM Publicartel\AppBundle\Entity\Content c WHERE c.categories.name = category
$categories is an atribute for the entity content.
class Content
{
private $categories;
public function __construct()
{
$this->categories = new \Doctrine\Common\Collections\ArrayCollection();
}
public function addCategories(\Publicartel\AppBundle\Entity\Category $categories)
{
$this->categories[] = $categories;
return $this;
}
public function removeCategories(\Publicartel\AppBundle\Entity\Category $categories)
{
$this->categories->removeElement($categories);
}
public function setCategories(\Publicartel\AppBundle\Entity\Category $categories = null)
{
$this->categories = $categories;
return $this;
}
public function getCategories()
{
return $this->categories;
}
}
The strange thing is that when I get get the variable , the error does not appear.
$category = $request->query->get('category');
You cannot reference subobject this way:
SELECT c FROM Publicartel\AppBundle\Entity\Content c WHERE c.categories.name = :category
You need to JOIN prior to that and use alias of that joined entity. Something like this:
SELECT c, cat FROM Publicartel\AppBundle\Entity\Content c JOIN c.categories cat WHERE cat.name = :category
Now, either use LEFT JOIN or just JOIN and it should work.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With