symfonydoctrine-orminsert-updatecreatequery

Is there possible to use createQueryBuilder for insert/update? If not, what function should I use?


For now I succeded to create a function that retrieves data from the database using Doctrine's function createQueryBuilder.

Does anybody know if there is a similar function to insert or update the database? Or how can i use createQueryBuilder?


Solution

  • Doctrine 2 ORM does not support INSERT via DQL or the DQL query builder. For a complete syntax, check the EBNF of DQL.

    To handle inserts in ORM, you always manually instantiate an entity and persist it with the entity manager:

    $user = new \My\Entity\User();
    
    $entityManager->persist($user);
    $entityManager->flush();
    

    You can only handle SELECT, UPDATE and DELETE via DQL in Doctrine ORM:

    You can handle these operations with the QueryBuilder as well:

        $queryBuilder = $entityManager->createQueryBuilder();
        $queryBuilder
            ->select('u')
            ->from('My\Entity\User', 'u')
            ->where($queryBuilder->expr()->eq('u.id', ':userId'));
    
        $queryBuilder = $entityManager->createQueryBuilder();
        $queryBuilder
            ->delete('My\Entity\User', 'u')
            ->where($queryBuilder->expr()->eq('u.id', ':userId'));
    
        $queryBuilder = $entityManager->createQueryBuilder();
        $queryBuilder
            ->update('My\Entity\User', 'u')
            ->set('u.status', 'banned')
            ->where($queryBuilder->expr()->eq('u.id', ':userId'));