如何在Doctrine中编写一个插入查询 [英] how to write an insert query in Doctrine

查看:144
本文介绍了如何在Doctrine中编写一个插入查询的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在Doctrine中创建一个将执行与以下SQL查询相同功能的插入查询:

How do I create an insert query in Doctrine that will perform the same function as the following SQL query:

INSERT INTO target (tgt_col1, tgt_col2) 
SELECT 'flag' as marker, src_col2 FROM source 
WHERE src_col1='mycriteria'


推荐答案

我仍然不相信这是正确的方法,但是如果你真的需要一个SQL查询来运行无论什么原因,您可以在Doctrine中使用 $ entityManager-> createNativeQuery(); 函数:

I'm still not convinced it's the right approach you are taking but if you really need an SQL query to be run for whatever reason you can do that in Doctrine with $entityManager->createNativeQuery(); function:

< a href =http://doctrine-orm.readthedocs.org/en/latest/reference/native-sql.html =nofollow> http://doctrine-orm.readthedocs.org/en/latest/ reference / native-sql.html

Doctrine不是用于查询操作的工具。整个想法是在实体级别工作,而不是SQL级别(表等)。 Doctrine的2 QueryBuilder 甚至不支持通过DQL INSERT 操作。

Doctrine isn't a tool for query manipulation. The whole idea is to work on Entity level, not the SQL level (tables, etc). Doctrine's 2 QueryBuilder doesn't even support INSERT operations via DQL.

下面的一小段伪代码,以说明如何在Doctrine的方式中完成:

A small snippet of pseudo code below to illustrate how it can be done in "Doctrine's way":

    $qb = $entityManager->createQueryBuilder();
    $qb->select('s')
        ->from('\Foo\Source\Entity', 's')
        ->where('s.col1 = :col1')
        ->setParameter('col1', 'mycriteria');

    $sourceEntities =  $qb->getQuery()->getResult();
    foreach($sourceEntities as $sourceEntity) {
        $targetEntity = new \Foo\Target\Entity();
        $targetEntity->col1 = $sourceEntity->col1;
        $targetEntity->col2 = $sourceEntity->col2;

        $entityManager->persist($targetEntity);
    }

    $entityManager->flush();

这篇关于如何在Doctrine中编写一个插入查询的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆