问题
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.
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.
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()
;
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.
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.
EDIT 1 I'm aware I could put the base data directly into the select()
call.
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
回答1:
From Doctrine 2.2 you can use HIDDEN
keyword for avability field in order by without hydration them.
Try:
->select('i, FIELD(i.id, :ids_string) AS HIDDEN fixed_order')
回答2:
You're going to kick yourself when you notice the problem...
Try re-reading your sentence: "so apparently it's not "seeing" the :ids_string in the select() method".
And then take a close look at your code: 'id_string' => implode(',', $itemIds)
来源:https://stackoverflow.com/questions/13689095/how-can-i-pass-a-parameter-to-a-doctrine2-custom-function-in-the-query-builder-s