Search code examples
sqlsymfonydoctrinedql

DQL query in Symfony for ManyToOne unidirectional relationship


class MenuItem
{
/**
* @ORM\Column(type="integer")
* @ORM\Id 
* @ORM\GeneratedValue(strategy="AUTO")
*/ 
protected $id; 

/**
* @ORM\ManyToOne(targetEntity="MenuCategory")
* @ORM\JoinColumn(name="menu_id", referencedColumnName="id")
*/
protected $catagory; 
}

Category class

class MenuCategory
{
/**
* @ORM\Column(type="integer")
* @ORM\Id
* @ORM\GeneratedValue(strategy="AUTO")
*/ 
protected $id; 

/**
* @ORM\Column(type="string")
*/ 
protected $name; 

/**
* @ORM\Column(type="integer")
*/
protectted $ordering;
}

I want to query all of the items ordered by the ordering property in the category. Here is my query that I tried. I am new to SQL/DQL and am not sure how to access the ordering property in the query. This query is the the MenuItemRepository.php file.

class MenuItemRepository extends EntityRepository
{ 
public function getOrderedMenu() 
{ 
   return $this->createQueryBuilder('i')
        ->select('i')
        ->orderBy('i.catagory.ordering', 'ASC') //????
        ->getQuery()
        ->getResult()
}
}

Is there a way to get all the items orderedBy ordering?


Solution

  • You have cat a gory in your orderBy clause instead of cat e gory!

    Further protectted instead of protected in front of your $ordering property.

    The following should work:

    return $this->createQueryBuilder('i')
        ->leftJoin('i.category', 'c')
        ->orderBy('c.ordering', 'ASC')
        ->getQuery()
        ->getResult();