简体   繁体   English

Symfony 4 - Doctrine DQL select 集合 ZA8CFDE6331BD59EB2AC66F8911C4B6 不起作用

[英]Symfony 4 - Doctrine DQL select collection object doesn't work

I have a problem with a DQL query on Symfony.我对 Symfony 的 DQL 查询有疑问。 In fact I have an entity Absence, and in the repository I want to return all absences, grouped by type of absence.事实上,我有一个实体缺勤,在存储库中我想返回所有缺勤,按缺勤类型分组。

For example we would have:例如,我们将有:

0 => array:2
    "absences" => Collection(or array, with all Absences objects)
    "type" => "Heures supp"
1 => array:2
    "absences" => Collection(or array, with all Absences objects)
    "type" => "RTT"
...

So I did my function:所以我做了我的 function:

public function getAbsencesValidees($user)
    {
        return $this->createQueryBuilder("a")
            ->select("a as absences, t.nom as type")
            ->join("a.typeConge", "t")
            ->where("a.user = :user")
            ->andWhere("a.etat = 'Validée'")
            ->groupBy("t.nom")
            ->setParameter("user", $user)
            ->getQuery()
            ->getResult();
    }

But suddenly in the attribute "absences", he puts me only the first object.但是突然在属性“缺席”中,他只给了我第一个 object。 He does not put me all the absences related to the guy.他并没有把我所有的缺席都与那个家伙有关。 However, if I withdraw the reference但是,如果我撤回参考

->groupBy("t.nom")

well I have all the absences, but suddenly it's not grouped So in the current state of things, I get this.好吧,我有所有的缺席,但突然它没有分组所以在当前的 state 中,我明白了。 So in the attribute "absences", he puts me only the first one that he finds and that corresponds, but he does not mention all the others who are part of it as well.因此,在“缺席”属性中,他只将我放在他找到并对应的第一个,但他没有提到所有其他人也是其中的一部分。

在此处输入图像描述

I think you misunderstand the use of groupBy() .我认为您误解了groupBy()的使用。
For what you want to do, you do not need groupBy() .对于您想要做的事情,您不需要groupBy()

First, your query:首先,您的查询:

public function getUserAbsences(User $user) {
    $qb=$this->createQueryBuilder("absence");

    $qb->addSelect("partial typeConge.{id, nom}")
       ->join("absence.typeConge", "typeConge")
       ->andWhere("absence.user = :user")
       ->andWhere("absence.etat = 'Validée'")
       ->setParameter("user", $user);

    return $qb->getQuery()->getResult();
}

Now, SQL result is not a multi-dimensional array, so in your controller, you have to filter this result.现在, SQL 结果不是多维数组,因此在您的 controller 中,您必须过滤此结果。

public function userAbsences(AbsenceRepository $absenceRepository) {
    $absencesByType=array();
    $absences=$absenceRepository->getUserAbsences($this->getUser());

    foreach($absences as $absence) {
        $absencesByType[$absence->getTypeConge->getNom][]=$absence;
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM