tags:

views:

116

answers:

1

assuming my setup is

Teachers (id, name)
Students (id, name, teacher [FK]);

how do i select in DQL teachers that have students? i guess it will be something like

select t FROM Entities\Teachers t WHERE count(t.students) > 0 

but i know count(t.students) > 0 is wrong ... what do i use then?

UPDATE

now what abt a many to many self referencing relationship? where a User can be a Teacher or Student or both ... code below ... whats the DQL for getting users that have students?

/** @Entity @Table(name="users")) */
class User {
    /**
     * @Id @Column(type="integer")
     * @GeneratedValue(strategy="AUTO")
     */
    private $id;
    /**
     * @Column(type="string", length="30")
     */
    private $name;
    /**
     * @ManyToMany(targetEntity="User", inversedBy="teachers")
     * @JoinTable(name="Teachers_Students",
     *              joinColumns={@JoinColumn(name="teacher", referencedColumnName="id")},
     *              inverseJoinColumns={@JoinColumn(name="student", referencedColumnName="id")}
     *              )
     */
    private $students;
    /**
     * @ManyToMany(targetEntity="User", mappedBy="students")
     */
    private $teachers;
+1  A: 

You can use a join in this case.

select t FROM Entities\Teachers as t 
innerjoin Entities\Students as s on t.id = s.teacher

If you can set up your base as like follows then you can handle you case very easily. So far from my experience I know doctrine can handle many to many relation within the best way.

$this->hasMany('User as Students', array(

        'local'     => 'id',

        'foreign'   => 'student_id',

        'refClass'  => 'UserToStudents',

        'onDelete'  => 'CASCADE'));

$this->hasMany('User as Teachers', array(

        'local'     => 'id',

        'foreign'   => 'teacher_id',

        'refClass'  => 'UserToTeachers',

        'onDelete'  => 'CASCADE')); 

Thanks

Muhit
ok, now to what i am doing a self referencing entity. see my update
jiewmeng
I have updated my comment. Please let me know clearly what else you want tot know.
Muhit
hmm... i am not familiar with this (but is this from doctrine 1.2? cos i am using 2.0). where is the code supposed to go? and where can i read the docs or whatever abt this?
jiewmeng