【问题标题】:Can I achieve a LIKE condition in a WHERE IN ARRAY query in doctrine?我可以在学说中的 WHERE IN ARRAY 查询中实现 LIKE 条件吗?
【发布时间】:2014-11-25 18:10:11
【问题描述】:

我正在使用 Doctrine QueryBuilder 创建一个查询,以通过电子邮件结尾选择一组用户。我有一系列电子邮件结尾,例如['@someservice.com', '@anotherservice.com' ].

我知道我可以通过WHERE IN 选择数组中的字符串:

$qb= $this
    ->createQueryBuilder('u')
    ->orderBy('u.id', 'asc')
    ->where('u.email IN (:emails)')
    ->setParameter('emails', [
        '@someservice.com',
        '@anotherservice.com'
    ]);

然而,此查询是针对字符串的确切出现,因此该查询当然会返回一个空结果集。

这就是为什么我想在数组上进行 LIKE 搜索,但要按照以下方式做一些事情:

$qb= $this
    ->createQueryBuilder('u')
    ->orderBy('u.id', 'asc')
    ->where('u.email LIKE IN (:emails)')
    ->setParameter('emails', [
        '%@someservice.com',
        '%@anotherservice.com'
    ]);

不幸的是失败了。是否有一些语法糖可以进行这样的查询,还是我必须使用一堆 orHaving 调用进行查询?

【问题讨论】:

  • LIKE IN 不是公认的 SQL 语法 AFAIK,因此可能不受支持。这并不妨碍您使用辅助函数对其进行扩展,该辅助函数将其转换为this solution 之类的东西。 HAVING 始终是最后的手段,这完全适合 WHERE。

标签: php arrays symfony doctrine-orm sql-like


【解决方案1】:

我通过以下方式实现了类似的目标:

foreach($emailEndings as $index => $ending) {
    $qb->orWhere("u.email LIKE :email$index");
    $qb->setParameter("email$index", $ending);
}

索引很重要,否则只会选择数组的最后一个条目。

请注意,如果您有多个 where 子句,您会因为 orWhere 子句而遇到麻烦。您不能将其更改为 andWhere,因为这会导致结果集为空。在该用例中,您需要将Orx 中的条件分组为andWhere,如下所示:

/**
 * @param QueryBuilder $qb
 */
protected function addInternalFilter(QueryBuilder $qb)
{
    $conditions = [];
    foreach ($this->emailEndings as $index => $ending) {
        $conditions[] = "u.email LIKE :string$index";
        $qb->setParameter("string$index", $ending);
    }

    if (empty($conditions)) {
        throw new \LogicException('Conditions are empty.');
    }

    $qb->andWhere(new Orx($conditions));
}

【讨论】:

  • @PawełKolanowski 你能详细说明一下吗?什么会更好?
  • 我的错误,对不起。乍一看,我认为也许解决更好,但似乎这种解决方案会有效。
【解决方案2】:

你不能这样做。 % 用于 LIKE,LIKE 不与 IN 一起使用。

您只能使用 OR 来处理它:

->where("u.email LIKE '%@someservice.com' OR u.email LIKE '%@anotherservice.com'")

【讨论】:

  • 我想避免避免每次添加新的电子邮件结尾时都维护一个选择查询。我想在配置数组中维护电子邮件结尾。因此迭代数组的重要性。
  • @k0pernikus 我知道,但你不能这样做,SQL 不会识别 LIKE IN 语法
猜你喜欢
  • 2016-10-30
  • 2023-03-31
  • 2014-03-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多