Note that there are some explanatory texts on larger screens.

plurals
  1. POHow to access properties of a related entity in a DQL query (Doctrine 2)?
    primarykey
    data
    text
    <p>I have set up a many to one relationship between a schools entity and students entity, I've linked the two together using a manyToOne relationship;</p> <p><strong>Students entity:</strong></p> <pre><code>/** * @var \Doctrine\Common\Collections\Collection * @ManyToOne(targetEntity="Schools", inversedBy="Students") * @JoinColumn(name="school_id", referencedColumnName="school_id") */ private $Schools; </code></pre> <p><strong>Schools entity:</strong></p> <pre><code>/** * @var \Doctrine\Common\Collections\Collection * @OneToMany(targetEntity="Students", mappedBy="Schools") */ private $Students; </code></pre> <p>This works as expected.</p> <p>I am trying to write a query for the Students table which specifies the school_id but I don't know how to specify this within the query;</p> <pre><code>$qb-&gt;select('t.position') -&gt;from('\Entities\Students', 't') -&gt;where($qb-&gt;expr()-&gt;eq('t.studentId', ':student_id')) -&gt;andWhere($qb-&gt;expr()-&gt;eq('t.Schools.schoolId', ':school_id')) // doesn't work -&gt;setParameters(array('student_id' =&gt; $this-&gt;studentId, 'school_id' =&gt; $school_id)); </code></pre> <p>I've attempted to access the school id through $Schools property I set up in the student identity but this throws an error.</p> <p>As a temporary fix I've created a $schoolId property in the Students entity and am using this instead but surely this is not the correct way to do this.</p> <p>Appreciate the help.</p> <p><strong>UPDATE</strong></p> <p>I got it to work by changing the line;</p> <pre><code>-&gt;andWhere($qb-&gt;expr()-&gt;eq('t.Schools.schoolId', ':school_id')) // doesn't work </code></pre> <p>To:</p> <pre><code>-&gt;andWhere($qb-&gt;expr()-&gt;eq('t.Schools', ':school_id')) </code></pre> <p>However the same approach doesn't work with the following query:</p> <pre><code>$qb-&gt;select('DISTINCT t.age, s.Schools') // Doesn't work -&gt;from('\Entities\Schools', 't') -&gt;innerJoin('t.Students', 's') </code></pre> <p>The following error is displayed:</p> <pre><code>[Semantical Error] line 0, col 28 near 'Schools FROM': Error: Invalid PathExpression. Must be a StateFieldPathExpression. </code></pre>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload