Doctrine fetch join

2019-04-08 14:44发布

问题:

First I will give an example with some pseudo code and then I will explain what is the problem. Let me say I have two entities User and Phonenumber. Their relation is one-to-many. In my UserRepository I can have something like that:

class UserRepository
{
    public function getUser($id, $type)
    {
        $users = $this->createQuery("SELECT u, p FROM User u JOIN u.phonenumbers p
            WHERE u.id = :id AND p.type = :type")
            ->setParameters(array(
                'id' => $id,
                'type' => $type,
            ))
            ->getResult();
        return $users[0];
    }
}

In my app if I have something like:

$user = $userRepo->getUser(1, 'home');
var_dump($user->getPhonenumbers()); // here phonenumbers collection is ok

$user = $userRepo->getUser(1, 'work');
var_dump($user->getPhonenumbers()); // Here phonenumbers collection is wrong.
                                // It's exactly the same as the previous one.

So my questions is: Is it possible to use fetch join (with different criteria) and to get the proper collection each time?

回答1:

Fetch joining and filtering a collection are not things that work together quite well. Here's how you should do it:

SELECT 
    u, p 
FROM 
    User u 
JOIN 
    u.phonenumbers p
JOIN
    u.phonenumbers p2
WHERE 
    u.id = :id 
    AND 
    p2.type = :type

This applies filtering on the second joined (and not hydrated) p2, which results in correct hydration and filtering.



回答2:

Use querybuilder, it is much simpler.

public function getUser($id, $type)
{
    return $this->createQueryBuilder("u")
        ->leftJoin("u.Phonenumbers", "p", "WITH", "p.type=:type")
        ->where("u.id=:id")
        ->setParameters(.....)
        ->getQuery()
        ->getOneOrNullResult() ;
}