I have a symfony problem: The functionally works good, but this does not work the way I want.

$res = array("4","2","1","3"); // LIST ID (a.id)
$paginas = new sfDoctrinePager('TbArticle', 2);
$paginas->setQuery(Doctrine::getTable('TbArticle')->createQuery('a')->where('a.ifactive = 1')->andWhere('a.dirimage=1')->andWhere('a.stock<>0')->whereIn("a.id", $res));
$paginas->setPage($page);
$paginas->init();

It works okay, but when I call getResults(), the array order is incorrect. For instance, this sort returns: 1,2,3,4. And I like to get: 4, 2, 1, 3 ($res)

Can you help me?

有帮助吗?

解决方案

Unfortubately this cannot be done with the query.

The MySQL queries can be returned ordered using the ORDER BY clause in ascending or descending order. Elements in your array use none. When you pass the array as a parameter for the WHERE IN clause MySQL doesn't care about the order of the elements as you can see.

Fortunately there is a solution :)

First you will have to use Doctrine's ability to create a table of results indexed with what you want. Use this:

Doctrine::getTable('TbArticle')->createQuery('a INDEX BY id')->...;

This will return an array of results where the array keys are the id's of the rows. Then you can rearange the results array to match your $res (assuming that $rows has the rows returned by Doctrine):

foreach ($res as $i) {
    $new_array[] = $rows[$i];
}

The tricky part is to make it work with the paginator. But I'm sure you can do that as well (try to retrieve the results from the paginator and rearange them before displaying).

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top