Php 推进WHERE IN子句和MySQL函数
最近,我开始使用Symfony和Propel 2.x进行编码,我在WHERE IN子句中遇到了一个问题 我想得到1993年和1988年出生的客户 因此,我编写了以下推进查询代码片段:Php 推进WHERE IN子句和MySQL函数,php,mysql,symfony,propel,Php,Mysql,Symfony,Propel,最近,我开始使用Symfony和Propel 2.x进行编码,我在WHERE IN子句中遇到了一个问题 我想得到1993年和1988年出生的客户 因此,我编写了以下推进查询代码片段: $query = ClientQuery::create() ->where('YEAR(Client.Birthdate) IN ?', [1993, 1988]) ->find(); 。。。ORM将这些整数映射为DateTime对象,因此最终查询如下所示: SELECT clien
$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')
有没有一种方法可以使用spreep构建如下所示的查询,而不使用原始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)
以使用别名进行选择,但也无法获得预期的查询
您可以尝试指定绑定类型:
->其中(‘年(客户出生日期)’,[1993年,1988年],PDO::PARAM_INT)
编辑:
是的,你说得对。此解决方案将导致proplexception,因为spreep/PDO无法将数组绑定到int
或者,您可以使用或设置以下条件:
$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();
我同意这个解决方案看起来不是很好,但它很有效。是的,看起来您必须使用4个条件:
$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();
- 出生日期>='1993-01-01'和出生日期>'1994-01-01'
- 或出生日期>='1988-01-01'和出生日期>'1989-01-01'
ClientQuery
类的condition()
和combine()
方法来实现这一点
我建议不要使用\u或()
方法
另外,我敢打赌,使用unix时间戳将使您的应用程序逻辑更容易构建查询。客户表中的birthdate是哪种类型的列?您能显示一些存储在int中的数据吗?@m1n0此列为日期类型。Propel认为我比较的是日期而不是INT,所以它将我的值转换为DateTime对象。不幸的是,它不起作用。Get-ProperteException:`无法执行SELECT语句[选择clients.id,clients.user\u id,clients.first\u name,clients.last\u name,clients.birthdate,clients.document\u id,clients.street,clients.postal\u code,clients.city,clients.country FROM clients WHERE YEAR(clients.birthdate)IN:p1中的客户所在年份]`此解决方案无法利用出生日期字段上的任何索引。ORM查询中的原始SQL。。。不会';使用不带spreep的原始SQL,或者了解如何在不带原始SQL的spreep中执行此查询,不是更好吗?