简体   繁体   中英

Symfony2 and Doctrine findOneById() without loading the associated entities?

Is it possible to get an entity without loading its associated entities using findOneById() ? In some cases such as just checking the entity exists or not, I don't need to load all of its associated entities, for example,

$entity = $em->getRepository('EstateBundle:MyEntity')->findOneById($id);
if (!$entity) {
    throw $this->createNotFoundException('Unable to find the entity.');
}

Otherwise, I think it could lead to performance issue. In CakePHP, it is possible using an option recursive . I'm looking for such kind of option in Symfony and Doctrine. I think this is a common question, but I can't find any documentation about this.

EDIT: removed the getReference possibility, as it is no solution for the question.

Second possibility is to change your entity by fetch="EXTRA_LAZY" Doctrine extra lazy

In general: Your assoiciated Entity is selected LAZY by default, means it only gets loaded, when first accessing it. Maybe your problem is not relevant in first place? To be sure use the development mode of Symfony. There you have the option to see, which database queries were actually executed.

EDIT: You can then use getRepository("bundle:entity")->find($id) to check existence. For actually querying it write a method like:

$q = $this->createQueryBuilder('o,u,i')
        ->select('o')
        ->from("bundle:entity","o")
        ->leftJoin("o.prop","u")
        ->leftJoin("o.prop2","i")
        ->where('o.id = :id')
        ->setParameter('id', $id)
        ->getQuery();

This then fetches the other entities as well.

Hope that helps

By default if you perform a findOneBy(), Doctrine will fetch only one entity with all its data, but not the relations. If you really want to check if the entity exists or not, add a select('id') statement, this way your object will be really small (the id will be hydrated nothing more).

Then if your object has relations, if you do $your_object->relations(). Doctrine will lazy load the relation leading to an extra query.

To prevent this from happening, you can forbid Doctrine's lazyloading by creating your own method :

 public function findMyObjectById($id)
    {
        $q = $this->createQueryBuilder('o')
            ->select('o.id')
            ->where('o.id = :id')
            ->setParameter('id', $id)
            ->getQuery()
            ->setHint(Query::HINT_FORCE_PARTIAL_LOAD, true);

        return ($q->getResult());
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM