我在从数据库中选择时遇到了问题。
基本上我想要实现的是:
我有一个包含 3 列的表
type | number | date
我需要根据列(类型)执行操作
If(type = 1) then where number > 1 else where date today()
因此,如果类型等于 1,则应用 number 的位置,否则应用 date 的位置。有可能做这样的事情吗?用 Laravel Eloquent 可以做到吗?
谢谢。
原始查询和数据类型为:type = string number = integer date = timestamp (Y-m-d H:i:s)
Query
SELECT * FROM table_name
WHERE CASE WHEN type = days THEN date > now() ELSE number > 0 END
表架构
CREATE TABLE banners (
id bigint(20) unsigned NOT NULL AUTO_INCREMENT,
type varchar(255) COLLATE utf8_unicode_ci NOT NULL DEFAULT '0',
number int(10) unsigned NOT NULL DEFAULT '0',
finish_at timestamp NOT NULL DEFAULT '0000-00-00 00:00:00',
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=12 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci
有效的解决方案:
select * from `banners`
where `banners`.`block_id` = 1 and `banners`.`block_id` is not null
and IF (`type` = 'days', `finish_at` > now(), `number` > 0)
拉拉维尔方式:
ParentModel::banners()->whereRaw("IF (`type` = 'days', `finish_at` > now(), `number` > 0)")->get();