【问题标题】:SQL doctrine query that has as many results as values ​passed in parametersSQL 学说查询,其结果与传入参数的值一样多
【发布时间】:2019-06-28 14:20:27
【问题描述】:

假设我给一个函数一个数组:

$arrValues = ['19', '4', '4', '18', '19']

到一个函数:

$objRequeteDoctrine = $this->getEntityManager()->createQueryBuilder()
    ->select('o')
    ->from('xxxxxx', 'o')
    ->where('o.id IN (:values)')
    ->andwhere('o.actif = 1')
    ->setParameter(':values', $arrValues );

return $objRequeteDoctrine->getQuery()->getResult();

在这里,它将检索 3 个对象(已删除重复项)。但是,如果我想检索 5 个带有重复项的对象怎么办?这可能吗?

谢谢。

【问题讨论】:

  • “重复”是什么意思?通常,SQL 查询不会返回任何重复项
  • 我的意思是这个查询将返回一个包含 3 个对象 xxxxx 的数组,来自 ids 19,4 和 18。但是有没有一个技巧来检索一个包含 5 个对象的数组,ids 19,4,4 ,18,19 ?
  • 如果你想实现这个,为什么不为此写一些代码呢?
  • 尝试制作一些UNION ALL(数组的每个值一个)也许?
  • 根据您的数据库,有时会有虚拟表之类的东西,您可以将其加入其中,从而多次从主表中获取行。我当然不会这样做。我会根据你的期望在 php 中填充数组。

标签: php sql symfony


【解决方案1】:

使用 Doctrine 实现这一目标可能不是您问题的答案,但可以解决您的问题。 之后如何生成完整的数组?

$arrValues = ['19', '4', '4', '18', '19'];

$objRequeteDoctrine = $this->getEntityManager()->createQueryBuilder()
    ->select('o')
    ->from('xxxxxx', 'o')
    ->where('o.id IN (:values)')
    ->andwhere('o.actif = 1')
    ->setParameter(':values', $arrValues );

$result = $objRequeteDoctrine->getQuery()->getResult();

// Get the object ids in a separate array to find their position in the result

$idsOnly = [];
foreach($result as $entity) {
    $idsOnly[] = $entity->getId();
}

// Find the key of the object by id in the first result

$fullResult = [];
foreach ($arrValues as $id) {
    $keyFound = array_search($id, $idsOnly);
    if ($keyFound !== false) {
        $fullResult[] = $result[$keyFound];
    }
}

return $fullResult;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-02-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-11-28
    • 1970-01-01
    相关资源
    最近更新 更多