I'm trying to make a native query with Doctrine 2.. but I can't make it works..
$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();
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 represent different objects, so, are not foreign key..
So, is it possible just to make a normal query to Doctrine 2 ?? .. I'm becoming crazy..
Thanks
It shouldn't be a problem if its a view or table as you get rows and columns from your query.
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.
You can check http://www.doctrine-project.org/docs/orm/2.0/en/reference/native-sql.html for more detailed examples.
UPDATE:
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.
Information about partial objects: http://www.doctrine-project.org/docs/orm/2.0/en/reference/partial-objects.html
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With