How To Utilize Doctrine2 Type Conversion on Native Query COLUMNS

独自空忆成欢 提交于 2019-12-12 12:06:48

问题


Could not find anything on this-- seems like it should be straight forward though.

So the example the Doctrine2 docs give for type conversion on bound parameters looks like this:

$date = new \DateTime("2011-03-05 14:00:21");
$stmt = $conn->prepare("SELECT * FROM articles WHERE publish_date > ?");
$stmt->bindValue(1, $date, "datetime");
$stmt->execute();

What I want to do is specify the type conversion for one of the columns, but there is nothing in the documents or on StackOverflow that I could find. A pseudo-example of what this might look like:

$stmt = $conn -> prepare("SELECT datetime FROM articles WHERE id = 1");
$stmt -> setType(0, "date_type"); // 0 being the column position, "date_type" being the PHP type to convert to

If anybody knows how to do this, (this is SQL not DQL), I would greatly appreciate. Thank you.


回答1:


This is not something that works at DBAL level. If you are using NativeSQL Queries in ORM, you can get that kind of conversion through hydration (see the NativeSQL section in the Doctrine ORM documentation) by using the HYDRATE_ARRAY mode and mapping some of the fetched fields to an entity. The fastest solution (if you don't intend to use ORM) is to iterate over the results and applying the type conversion manually by accessing Doctrine\DBAL\Types\Type::getType($someType)->convertToPhpValue($fetchedValue). It could be a valuable addition to ORM to be able to specify a third parameter stating the fetched type in Doctrine\ORM\Query\ResultSetMapping#addScalarResult.



来源:https://stackoverflow.com/questions/11483888/how-to-utilize-doctrine2-type-conversion-on-native-query-columns

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!