在Symfony2中使用nativeQuery检索对象

时间:2013-12-12 17:10:48

标签: symfony doctrine-orm

我想在Symfony 2中检索具有本机查询的对象

我的代码是:

$rsm = new ResultSetMapping($this->getEntityManager());
        $rsm->addEntityResult('SNUserBundle:User', 'u');
        $rsm->addFieldResult('u', 'nickname', 'nickname');

        $query = $this->getEntityManager()->createNativeQuery('SELECT u.nickname FROM u WHERE u.nickname = ?', $rsm);
        $query->setParameter(1, 'barno7');


        $users = $query->getResult();

我有这个错误

An exception occurred while executing 'SELECT u.nickname FROM u WHERE u.nickname = ?' with params ["barno7"]:

SQLSTATE[42S02]: Base table or view not found: 1146 Table 'sn.u' doesn't exist

我的表名sn_user和我的实体SNUserBundle:用户有这个注释

 * @ORM\Table(name="sn_user")

我也尝试

$query = $this->getEntityManager()->createNativeQuery('SELECT u.nickname FROM user WHERE u.nickname = ?', $rsm);

我的错误是

An exception occurred while executing 'SELECT u.nickname FROM users WHERE u.nickname = ?' with params ["barno7"]:

SQLSTATE[42S02]: Base table or view not found: 1146 Table 'sn.user' doesn't exist

我真正的桌子是sn_user

2 个答案:

答案 0 :(得分:2)

我认为你混淆了SQL和DQL,或者使用它们的函数。看起来您想要使用DQL进行查询,这将返回一个对象。在这种情况下,您不使用createNativeQuery方法。这种方法适用于SQL。

有关如何使用DQL进行查询的示例,请参阅Symfony docs on DQL。以下是文档中的示例代码段:

$em = $this->getDoctrine()->getManager();
$query = $em->createQuery(
    'SELECT p
    FROM AcmeStoreBundle:Product p
    WHERE p.price > :price
    ORDER BY p.price ASC'
)->setParameter('price', '19.99');

$products = $query->getResult();

遵循这个语法,你应该没问题。

答案 1 :(得分:0)

我这样解决

$rsm = new ResultSetMapping;
    $rsm->addEntityResult('SNUserBundle:User', 'u');
    $rsm->addFieldResult('u', 'id', 'id');
    $rsm->addFieldResult('u', 'n', 'nickname');

    $query = $this->getEntityManager()->createNativeQuery('
    SELECT u.id ,u.nickname as n FROM sn_user u WHERE u.nickname LIKE = ?', $rsm);
    $query->setParameter(1, 'barno7');       

    $users = $query->execute();
    return $users;