php - 推进 WHERE IN 子句和 MySQL 函数

标签 php mysql symfony propel

最近我开始使用 Symfony 和 Propel 2.x 进行编码,并且遇到了 WHERE IN 子句的问题。

我想要获得 1993 年和 1988 年出生的客户。

所以我写了这个 Propel Query 代码片段:

$query = ClientQuery::create()
    ->where('YEAR(Client.Birthdate) IN ?', [1993, 1988])
    ->find();

...并且 ORM 将这些整数映射为 DateTime 对象,因此最终查询如下所示:

SELECT clients.id, clients.user_id, clients.first_name, clients.last_name, clients.birthdate, clients.document_id, clients.street, clients.postal_code, clients.city, clients.country 
FROM clients 
WHERE YEAR(clients.birthdate) IN ('1970-01-01','1970-01-01')

有没有办法使用 Propel 构建如下查询,而不使用 RAW SQL 查询?

SELECT clients.id, clients.user_id, clients.first_name, clients.last_name, clients.birthdate, clients.document_id, clients.street, clients.postal_code, clients.city, clients.country 
    FROM clients 
    WHERE YEAR(clients.birthdate) IN (1993, 1988)

我尝试将 YEAR(clients.birthdate) 添加到带有别名的 SELECT 中,但也无法获得预期的查询。

最佳答案

<删除> 您可以尝试指定绑定(bind)类型: ->where('YEAR(Client.Birthdate) IN ?', [1993, 1988], PDO::PARAM_INT)

编辑:

是的,你说得对。此解决方案将导致 PropelException,因为 Propel/PDO 无法将数组绑定(bind)到 int。

或者,您可以使用 OR 条件:

  $years = [1993, 1988];
  // Get the key of the first element
  $firstKey = key($years);
  $query = ClientQuery::create();
  foreach ($years as $key => $year) {
      // Add _or() call for all elements except the first one
      if ($key !== $firstKey) {
          $query->_or();
      }
      // Add where condition and binding type
      $query->where('YEAR(Client.Birthdate) = ?', $year, PDO::PARAM_INT);
  }
  $query = $query->find();

我同意这个解决方案看起来不太好,但它有效。

关于php - 推进 WHERE IN 子句和 MySQL 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44442581/

相关文章:

php - WooCommerce 序列化 wp_postmeta 表中的元值数组

PHP 和 MS.NET 比较

MySQL - 在嵌入式程序的情况下回滚事务

mysql - 通过 JOIN 导出 MySQL 表?

php - 发送电子邮件时出错 [Symfony mailerBundle]

php - 查询给我一个 bool 错误

php - 来自两个表的 SQL 查询按两个表列排序结果

php - 在 TWIG 中渲染多维数组

php - 如何获取实体关联的旧值?

php - 尝试在 PHP 中通过 JSON 发送 URL 时遇到问题