Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
753 views
in Technique[技术] by (71.8m points)

symfony - 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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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 MyEntityUser();

$entityManager->persist($user);
$entityManager->flush();

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

  • Select:

    SELECT u FROM MyEntityUser u WHERE u.id = :userId
    
  • Update:

    UPDATE MyEntityUser u SET u.status = 'banned' WHERE u.id = :userId
    
  • Delete

    DELETE MyEntityUser u WHERE u.id = :userId
    

You can handle these operations with the QueryBuilder as well:

  • Select:
    $queryBuilder = $entityManager->createQueryBuilder();
    $queryBuilder
        ->select('u')
        ->from('MyEntityUser', 'u')
        ->where($queryBuilder->expr()->eq('u.id', ':userId'));
  • Delete:
    $queryBuilder = $entityManager->createQueryBuilder();
    $queryBuilder
        ->delete('MyEntityUser', 'u')
        ->where($queryBuilder->expr()->eq('u.id', ':userId'));
  • Update:
    $queryBuilder = $entityManager->createQueryBuilder();
    $queryBuilder
        ->update('MyEntityUser', 'u')
        ->set('u.status', 'banned')
        ->where($queryBuilder->expr()->eq('u.id', ':userId'));

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...