简体   繁体   English

如何在Symfony2 Doctrine2中将varchar命令为int?

[英]How to order varchar as int in Symfony2 Doctrine2?

I have the following code: 我有以下代码:

$entity = $em->getRepository('MyBundle:MyEntity')
    ->createQueryBuilder('q')
    ->...
    ->orderBy('q.varcharCol')
    ->getQuery()
    ->getResult();

varcharProp is a varchar column containing values such as: 10, 10a, 101, 20, 300, 20b, 21, 200. I want to sort my entity by varcharProp but casting it as integer and I must do this ordering inside the query because I'm limiting the results. varcharProp是一个包含以下值的varchar列:10,10a,101,20,300,20b,21,200。我想通过varcharProp对我的实体进行排序,但是将它作为整数进行排序,我必须在查询中进行此排序,因为我限制结果。

It's possible to do something like this in Doctrine2? 在Doctrine2中可以做这样的事情吗?

entity->orderBy('ABS(q.varcharCol)')

Or changing varcharProp column type? 或者更改varcharProp列类型?

The best way to approach this is adding a select with the orderBy expression as a hidden column. 解决这个问题的最佳方法是使用orderBy表达式添加一个select作为隐藏列。 I mean: 我的意思是:

$entity = $em->getRepository('MyBundle:MyEntity')
    ->createQueryBuilder('q')
    ->addSelect('ABS(q.varcharCol) AS HIDDEN foo')
    ->...
    ->orderBy('foo')
    ->getQuery()
    ->getResult();

Thanks to @Qoop and @eggyal 感谢@Qoop和@eggyal

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM