我从DB中选择了问题.
基本上我想要实现的是:
我有一个有3列的表
type | number | date
我需要做基于列(类型)的地方
If(type = 1) then where number > 1 else where date today()
因此,如果type等于1,则将数字应用于数字,否则应用于何处.有可能这样想吗? Laravel Eloquent可以做到吗?
谢谢.
原始查询和数据类型是:
type = string
number =整数
date = timestamp(Y-m-d H:i:s)
询问
SELECT * FROM table_name
何时类型=天数日期>现在()ELSE数字> 0 END
表模式
CREATE TABLE横幅(
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′,
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)
Laravel方式:
ParentModel::banners()->whereRaw("IF (`type` = 'days', `finish_at` > now(), `number` > 0)")->get();
解决方法:
你可以像使用它一样使用它
SELECT * FROM tablename WHERE IF (`type` = 1, `number` > 1,`date` = today())
使用Laravel Eloquent,您可以像使用它一样使用它
ModelName::whereRaw('IF (`type` = 1, `number` > 1,`date` = today())')->get();
标签:php,mysql,laravel,eloquent
来源: https://codeday.me/bug/20190609/1202643.html