Hari
Hari

Reputation: 1623

Understanding Doctrine Query Builder?

lets say i have department,college entities like follow

class Department{
     private $name;

     private $studentCount;


    /**  
    *@ORM\ManyToOne(targetEntity="\CAPP\CollegeBundle\Entity\College", inversedBy="departments")
    *@ORM\JoinColumn(name="college_id", referencedColumnName="id", nullable=false)
    **/
     private $college
}

class College
{

   private $name;

   private $departmentCount;

   /**
   *@ORM\OneToMany(targetEntity="\CAPP\DepartmentBundle\Entity\Department", mappedBy="college", cascade={"all"}, orphanRemoval=true)
   */
   private $departments
}

when i write a doctrine query builder to fetch all department with following query

METHOD1:
return $this->getQb()->select("dp")
            ->from("DepartmentBundle:Department", "dp")
            ->getQuery()
            ->getResult()
            ;

I got my result with all the fields,but when i am trying to access particular fields such name and college, with the following query

METHOD2:
return $this->getQb()->select("dp.name, dp.college")
            ->from("DepartmentBundle:Department", "dp")
            ->getQuery()
            ->getResult()
            ;

i am getting error like

col 10 near 'college FROM': Error: Invalid PathExpression. Must be a StateFieldPathExpression.

what mistake i made here, doctrine fetches all departments with respective college entities on query method 1, but when i try query method 2 why it throws error.

Upvotes: 0

Views: 425

Answers (3)

UUake Up
UUake Up

Reputation: 400

Not sure if this is any way the best answer but I'd just grab the collection and then use the get/set methods to pull the info...

$department = $this->getQb()->select("dp")
            ->from("DepartmentBundle:Department", "dp")
            ->getQuery()
            ->getResult();

$name = $department->getName(); 
$college = $department->getCollege(); 

Upvotes: 0

goto
goto

Reputation: 8162

Doctrine discourage using partial object if it is not purelly for optimization. You should use doctrine as intended: fully object oriented.

$this->getQb('dp')
    ->select("dp")
    ->from("DepartmentBundle:Department", "dp")

If you really want to use partial:

$this->getQb('dp')
    ->select("partial dp.{name,college}")
    ->from("DepartmentBundle:Department", "dp")

Upvotes: 2

Alessandro Minoccheri
Alessandro Minoccheri

Reputation: 35973

try this please:

return $this->getQb('dp')->select('IDENTITY(dp.name)', 'IDENTITY(dp.college)')
            ->from("DepartmentBundle:Department", "dp")
            ->getQuery()
            ->getResult()
            ;

If dp.name, or dp.college are composite keys then you need to add IDENTITY in order to make the query work and fix the issue

Upvotes: 0

Related Questions