【问题标题】:Symfony / Doctrine - How can I symplify this code?Symfony / Doctrine - 我怎样才能简化这段代码?
【发布时间】:2016-09-24 10:53:01
【问题描述】:

我在 symfony 中有两个表,通过 ManyToOne 双向关系连接。文章和日期。

我得到了除 a.id : 4 之外的所有文章,因为其中一篇没有响应条件。

我找到了解决方案,但如何简化它?我知道它没有优化。我愿意。

在我的表(日期)中,我有:

+----------------------------
| id   | a.id  | OK OR NOT ? 
+----------------------------
| 1    | 4     |      OK 
| 2    | 4     |      OK 
| 3    | 6     |      OK 
| 4    | 5     |      OK 
| 5    | 4     |   **NOTOK** 
----------------------------

    $qb = $this->createQueryBuilder('a');
    $allIndispo = $qb
        ->select('a.id')
        ->leftJoin('a.dates','d')
        ->where('**NOTOK**')
        ->orderBy('a.id', 'ASC')
        ->getQuery()
        ->getResult();

    $allIndispoId = array();
    foreach ($allIndispo as $key => $value) {
        foreach ($allIndispo[$key] as $key2 => $value2) {
            $allIndispoId[] = $value2;
        }
    }

    $allDispo = $this->createQueryBuilder('a')
        ->select('a')
        ->where($qb->expr()->notIn('a.id', "'".implode($allIndispoId, "', '")."'"))
        ->getQuery()
        ->getResult();

    return $allDispo;

【问题讨论】:

    标签: php sql doctrine-orm symfony


    【解决方案1】:

    尝试将第一个查询用作第二个查询的子查询,例如:

    $qb = $this->createQueryBuilder('a2');  //We need a different alias here
        $allIndispo = $qb
            ->select('a2.id')
            ->leftJoin('a2.dates','d')
            ->where('**NOTOK**') // so take care to change the table alias here also
            ->orderBy('a2.id', 'ASC');
    
    
    $allDispo = $this->createQueryBuilder('a')
        ->select('a')
        ->where($qb->expr()->notIn('a.id', $subQuery->getDQL()))
        ->getQuery()
        ->getResult();
    
    return $allDispo;
    

    希望有帮助

    【讨论】:

      猜你喜欢
      • 2023-03-05
      • 1970-01-01
      • 2022-01-11
      • 1970-01-01
      • 2017-08-15
      • 1970-01-01
      • 1970-01-01
      • 2023-02-05
      • 1970-01-01
      相关资源
      最近更新 更多