php - Laravel where if 语句

标签 php mysql laravel eloquent

我遇到了从数据库中选择的问题。 基本上我想要实现的是: 我有一个包含 3 列的表格

type | number | date

我需要根据列(类型)在哪里做

If(type = 1) then where number > 1 else where date today()

因此,如果类型等于 1,则应用编号,否则应用日期。有可能做这样的事情吗?可以用 Laravel Eloquent 做到吗? 谢谢。

原始查询和数据类型为: type = string number = integer date = timestamp (Y-m-d H:i:s)

查询

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)

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 - Laravel where if 语句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33473053/

相关文章:

c# - 使用 Rijndael 进行跨平台(php 到 C# .NET)加密/解密

php - 仅当另一个字段有值时才为必填字段,否则必须为空

php - 在 CMS 中选择页面 View /布局

php - Nette Framework - 将所有内容路由给一位演示者

phpwebsockets yii 实现

mysql - 优化 SQLAlchemy 中的hybrid_properties

mysql - count(*) 返回负值

Laravel 混合 : These dependencies were not found:

javascript - 使用隐藏输入是在外部 JavaScript 文件中检索 php 变量的有效方法吗?

mysql - 优化MySQL单表2800万行聚合查询