最近我开始使用 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/