我正在使用QueryBuilder来获取项目中所有连接的所有产品的查询。然后我使用分页在前端显示它们。有时我需要按特定顺序获取它们,但我无法在QueryBuilder中找到一种方法。
例如,一个查询按id返回产品:70,71,72,73,74,75 但如果我有一些自定义订单,我想显示它:72,74,75,70,71,73
所以在我的querybuilder中我做了这样的事情:
public function querySortedProductsInCategories($id, $type, $slug, $sort)
{
$qb = $this->createQueryBuilder('p');
$qb->addSelect(array('p', 'gallery'));
$qb->addSelect(array('p', 'media'));
$qb->addSelect(array('p', 'image'));
$qb->leftJoin("p." . $type, "c");
$qb->leftJoin('p.gallery', 'gallery');
$qb->leftJoin('gallery.galleryHasMedias', 'media');
$qb->leftJoin('media.media', 'image');
$qb->where("c." . $type. "= :id ");
$qb->andWhere($qb->expr()->in('p.id', $sort));
$qb->SetParameter('id', $id);
return $qb->getQuery();
}
生成的查询如下所示:
'SELECT p, p, gallery, p, media, p, image FROM Mp\ShopBundle\Entity\Product p LEFT JOIN p.subcategory c LEFT JOIN p.gallery gallery LEFT JOIN gallery.galleryHasMedias media LEFT JOIN media.media image WHERE c.subcategory= :id AND p.id IN('70', '73', '76', '72', '71', '74')'
但返回的数组是由Id ...
订购的如果我尝试做类似的事情:
$qb->orderBy("p.id", $sort);
但是当然我得到array to string conversion
错误......
有什么方法可以做到这一点?
答案 0 :(得分:0)
public function querySortedProductsInCategories($id, $type, $slug, $sort)
{
$qb = $this->createQueryBuilder('p');
$qb->addSelect(array('p', 'gallery'));
$qb->addSelect(array('p', 'media'));
$qb->addSelect(array('p', 'image'));
$qb->leftJoin("p." . $type, "c");
$qb->leftJoin('p.gallery', 'gallery');
$qb->leftJoin('gallery.galleryHasMedias', 'media');
$qb->leftJoin('media.media', 'image');
$qb->where("c." . $type. "= :id ");
$qb->andWhere('p.id IN(:ids)');
$qb->setParameter('ids', $id);
$qb->orderBy('p.id', 'ASC'); // change to $sort if $sort either ASC or DESC
return $qb->getQuery();
}
这有用吗?
答案 1 :(得分:0)
你可以通过使用doctrine的queryBuilder的 indexBy 参数来实现这个技巧
公共函数来自($ from,$ alias,$ indexBy = null);
这会将结果数组的索引设置为此paramareter中字段的值。
然后你可以按照你的方式重新排序这个数组
public function querySortedProductsInCategories($id, $type, $slug, $sort)
{
$qb = $this->createQueryBuilder('p');
$qb->from('Product', 'p', 'p.id';
[... the rest of your query]
$result = $qb->getQuery()->getResult();
// Here you have an array indexed by the id of your products and you can order it using your $sort array of products ids
uksort($result,
function ($key1,$key2) use ($sort) {
$product1Position = array_search($key1,$sort);
$product2Position = array_search($key2,$sort);
if ( $product1Position === false || $product2Position === false) {
return 0;
}
return ($product1Position < $product2Position) ? -1 : 1;
}
);
return $result;
}
来源: http://doctrine-orm.readthedocs.io/projects/doctrine-orm/en/latest/reference/query-builder.html#high-level-api-methods http://php.net/manual/en/function.uksort.php
祝你好运