为什么我有 EntityManagerGhostEbeb667 作为 Doctrine 结果

问题描述 投票:0回答:1

当我在存储库中使用 createQueryBuilder 时:

if (!$user) {
    $result = $this->createQueryBuilder('m')
        ->andWhere('m.message_from is null and m.is_deleted_by_sender = false')
        ->orWhere('m.message_to is null and m.is_deleted_by_receiver = false')
        ->addOrderBy('m.is_read', 'ASC')
        ->addOrderBy('m.created_at', 'DESC')
        ->getQuery()
        ->getResult();
} else {
    $result = $this->createQueryBuilder('m')
        ->andWhere('m.message_from = :user and m.is_deleted_by_sender = false')
        ->orWhere('m.message_to =:user and m.is_deleted_by_receiver = false')
        ->setParameter('user', $user)
        ->addOrderBy('m.is_read', 'ASC')
        ->addOrderBy('m.created_at', 'DESC')
        ->getQuery()
        ->getResult();
}

我得到了好的结果:

但是,当我通过删除重复来优化代码时,如下所示:

$result = $this->createQueryBuilder('m');

if (!$user) {
    $result
        ->andWhere('m.message_from is null and m.is_deleted_by_sender = false')
        ->orWhere('m.message_to is null and m.is_deleted_by_receiver = false');
} else {
    $result
        ->andWhere('m.message_from = :user and m.is_deleted_by_sender = false')
        ->orWhere('m.message_to =:user and m.is_deleted_by_receiver = false')
        ->setParameter('user', $user);
}

$result
    ->addOrderBy('m.is_read', 'ASC')
    ->addOrderBy('m.created_at', 'DESC')
    ->getQuery()
    ->getResult();

我得到这个结果:

我的问题是:为什么?

我还有其他功能和优化的代码,而且效果很好

php mysql symfony doctrine query-builder
1个回答
0
投票

你在倾倒吗

$result

您需要检索结果,而不是作为查询构建器的 $result 对象。

你可能正在做这样的事情:

$result = $this->createQueryBuilder('m');

// ...

$result
    ->addOrderBy('m.is_read', 'ASC')
    ->addOrderBy('m.created_at', 'DESC')
    ->getQuery()
    ->getResult();

dump($result);

但是你应该使用 $result->getQuery()->getResult() 的结果而不是 $result。

所以要么退货

return $result
    ->addOrderBy('m.is_read', 'ASC')
    ->addOrderBy('m.created_at', 'DESC')
    ->getQuery()
    ->getResult();

或者像您的第一个版本一样在变量中使用它:

$result = $result
    ->addOrderBy('m.is_read', 'ASC')
    ->addOrderBy('m.created_at', 'DESC')
    ->getQuery()
    ->getResult();

您的方法的干净版本将如下所示:

$qb = $this->createQueryBuilder('m');

if (!$user) {
    $qb->andWhere('m.message_from is null and m.is_deleted_by_sender = false')
       ->orWhere('m.message_to is null and m.is_deleted_by_receiver = false');
} else {
    $qb->andWhere('m.message_from = :user and m.is_deleted_by_sender = false')
       ->orWhere('m.message_to =:user and m.is_deleted_by_receiver = false')
       ->setParameter('user', $user);
}

return $qb
    ->addOrderBy('m.is_read', 'ASC')
    ->addOrderBy('m.created_at', 'DESC')
    ->getQuery()
    ->getResult();
© www.soinside.com 2019 - 2024. All rights reserved.