原则2,原生查询 [英] Doctrine 2, Native Query

查看:108
本文介绍了原则2,原生查询的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

I'm trying to make a native query with Doctrine 2.. but I can't make it works..

我试图用Doctrine 2 .. > $ q =SELECT * FROM user_recent_activity WHERE id = {$ user-> id};
$ rsm = new \Doctrine\ORM\Query\ResultSetMapping;
$ query = $ this-> _em-> createNativeQuery($ q,$ rsm);
$ result = $ query-> getResult();

$q = "SELECT * FROM user_recent_activity WHERE id = {$user->id}"; $rsm = new \Doctrine\ORM\Query\ResultSetMapping; $query = $this->_em->createNativeQuery($q, $rsm); $result = $query->getResult();

这是返回空数组..我不知道它是如何工作的ResultSetMapping,但我这个查询无法映射,就像我在doctrine网站的例子中看到的那样,因为user_recent_activity它不是一个表,它是这样的视图:

This is returning empty array.. I'm not sure how it works "ResultSetMapping", but I can't Map nothing with this query as I have seen in examples in doctrine website, because user_recent_activity it's not a table, it's a view like this:

id  user_id  type     created_at
12  5        opinion  2011-02-22 23:29:00
2   2       vote     2011-01-30 14:16:51

id表示不同的对象,所以不是外键..

id represent different objects, so, are not foreign key..

那么,是否可以只对Doctrine 2进行正常查询? ..我变得疯了..

So, is it possible just to make a normal query to Doctrine 2 ?? .. I'm becoming crazy..

谢谢

推荐答案

如果您从查询中获取行和列,它的视图或表格不应该是一个问题。

It shouldn't be a problem if its a view or table as you get rows and columns from your query.

您需要将结果映射到本机sql查询的实体使用rsm。

You need to map the results to entities for native sql queries using rsm.

$rsm->addEntityResult('UserRecentActivity', 'u');
$rsm->addFieldResult('u', 'id', 'id');
$rsm->addFieldResult('u', 'user_id', 'user_id');
$rsm->addFieldResult('u', 'type', 'type');
$rsm->addFieldResult('u', 'created_at', 'created_at');

您还应该有适当的实体。

And you should have the appropriate entity as well.

您可以查看 http://www.doctrine-project .org / docs / orm / 2.0 / en / reference / native-sql.html 以获取更多详细示例。

You can check http://www.doctrine-project.org/docs/orm/2.0/en/reference/native-sql.html for more detailed examples.

更新:

如果视图包含多于1个表的结果,则可以使用addJoinedEntityResult()方法将结果映射到其各自的实体。您需要相应地定义实体,并将结果映射到其字段。

In case of views that contains results from more than 1 table, addJoinedEntityResult() method can be used to map the results to their respective entities. You need to define the entities accordingly and map the results to their fields.

此方法可能最终会部分对象,因此应仔细使用此方法以避免数据损坏。

This method will probably end up with partial objects, so it should be used carefully to avoid data corruption.

有关部分对象的信息: http://www.doctrine-project.org/docs/orm/2.0/en/reference/partial-objects.html

Information about partial objects: http://www.doctrine-project.org/docs/orm/2.0/en/reference/partial-objects.html

这篇关于原则2,原生查询的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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