【问题标题】:Laravel 5: Query Builder: Get the record using date in datetime datatypeLaravel 5:查询生成器:使用日期时间数据类型中的日期获取记录
【发布时间】:2020-05-17 19:17:30
【问题描述】:

我有日期列,数据类型是日期时间,现在我想获取所有与某个日期相关的日期。

我想监控我在某一年购买了多少物品,但我现在拥有的是,我没有得到任何价值。

示例

我的日期是:

$date['start_date'] = "2019-01-01";
$date['end_date']   = "2019-12-31";

我有 3 条记录

1) 
   name: Laptop
   date(date bought): 2018-03-05 14:23:00
2) 
   name: Shoes
   date(date bought): 2019-03-05 23:05:00
3) 
   name: Bag
   date(date bought): 2019-10-05 18:35:00

型号

return DB::table('x')
      ->whereBetween('date', [date('Y-m-d', strtotime($date['start_date'])), date('Y-m-d', strtotime($date['end_date']))])
->get()->toArray();

问题:我的查询有误吗?

【问题讨论】:

  • 请张贴$date['start_date']$date['end_date']
  • 更新了我的帖子,
  • 你忘了->get() mehod
  • 再次更新了我的帖子。
  • date('Y-m-d', strtotime($date['start_date']))$date['start_date'] 相同。

标签: laravel query-builder


【解决方案1】:

您可以像在普通 SQL 中一样使用 like,并将日期时间字段视为文本字段

 return DB::table('x')->where('date', 'like', "2019-%")->get()->toArray();

你的模型甚至更好

 return YourModelX::where('date', 'like', "2019-%")->get()->toArray();

或者您使用 whereBetween 与数据库中单元格的格式:

// datetime
return YourModelX::whereBetween('date', ['2019-01-01 00:00:00','2019-12-31 23:59:59'])->get();
// date
return YourModelX::whereBetween('date', ['2019-01-01','2019-12-31'])->get();

【讨论】:

  • 不,因为它不是作为日期时间处理,而是作为字符串处理
  • 比如2018年买的东西,不显示?因为只有 2019-%?因为我已经对此进行了过滤,所以用户将选择年/月/日
  • MySQL 具有处理日期的函数,您不应该将它们视为文本 - 单独的性能会更差。除非您有一个精心构建的索引,否则使用 LIKE 会翻倍。在给定的示例中,MySQL's YEAR() 函数会更有意义,对应的whereYear() in Laravel。这一切都没有实际意义,因为该查询无论如何都对 OP 没有帮助,但想指出这不是一个好方法。
猜你喜欢
  • 1970-01-01
  • 2011-07-09
  • 1970-01-01
  • 2012-03-18
  • 2014-12-30
  • 1970-01-01
  • 2017-03-01
  • 1970-01-01
  • 2015-08-17
相关资源
最近更新 更多