如何在Query Builder select()方法中将参数传递给Doctrine2自定义函数? [英] How can I pass a parameter to a Doctrine2 custom function in the Query Builder select() method?
问题描述
在我的Symfony2项目中,我从一个弹性搜索索引中检索一组有序的实体ID。然后,我将这个列表传递给Doctrine2,以通过 WHERE IN()
调用来检索实际的实体。
In my Symfony2 project I am retrieving an ordered set of entity IDs from an Elasticsearch index. I'm then passing this list to Doctrine2 to retrieve the actual entities, by way of a WHERE IN()
call.
这不会以正确的顺序返回,所以我想我需要使用MySQL特定的 FIELD()
函数。我已经创建了一个自定义的DQL函数来允许这个功能。
This doesn't return them in the correct order, so I think I need to use the MySQL-specific FIELD()
function. I've created a custom DQL function to allow the functionality.
所以现在我使用下面的代码构建一个Doctrine查询对象,但参数不是被解析成 select()
方法:
So now I'm using the following code to build a Doctrine query object, but the parameters aren't being parsed into the select()
method:
$itemIds = array(4,8,2,1);
$this->getRepository()
->createQueryBuilder('i')
->select('i, FIELD(i.id, :ids_string) AS HIDDEN fixed_order')
->where('i.id IN (:ids)')
->setParameters(array(
'ids_string' => implode(',', $itemIds),
'ids' => $itemIds))
->orderBy('fixed_order', 'ASC')
->getQuery()
;
失败,错误参数号无效:绑定变量的数量不符合令牌数
,所以显然不是在 select()
This fails with the error "Invalid parameter number: number of bound variables does not match number of tokens"
, so apparently it's not "seeing" the :ids_string
in the select()
method.
我最初尝试将 FIELD()
函数放在 orderBy()
调用,但它看起来不像为自定义DQL函数调用得到解析,我想我会遇到与上述相同的问题。
I initially tried putting the FIELD()
function in the orderBy()
call, but it doesn't look like this is getting parsed for custom DQL function calls, and I imagine I'd run into the same problem as above.
编辑1 我知道我可以将基础数据直接放入 select()
调用中。
EDIT 1 I'm aware I could put the base data directly into the select()
call.
编辑2 我已经放弃了将裸体数据放入 select()
call(我想避免的)。这是有效的,但是后来需要实现Koc关于使用 HIDDEN
关键字的建议,以防止Doctrine返回 array(Object i,array(fixed_order))
而不是 Object i
EDIT 2 I've given up and put the bare data into the select()
call (which I wanted to avoid). This worked, but then it became necessary to implement Koc's suggestion of using the HIDDEN
keyword to prevent Doctrine returning array(Object i, array(fixed_order))
instead of just Object i
推荐答案
当你注意到这个问题的时候,你会踢自己的事情。
You're going to kick yourself when you notice the problem...
尝试重读你的句子:显然这并不是看到了: select()方法中的ids_string
Try re-reading your sentence: "so apparently it's not "seeing" the :ids_string in the select() method".
然后仔细看看你的代码:'id_string' => implode(',',$ itemIds)
And then take a close look at your code: 'id_string' => implode(',', $itemIds)
这篇关于如何在Query Builder select()方法中将参数传递给Doctrine2自定义函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!