【问题标题】:Eloquent model between dates format d.m.Y日期格式 d.m.Y 之间的 Eloquent 模型
【发布时间】:2016-04-14 08:40:54
【问题描述】:

我有字符串类型的列“exp_date”,列的格式是 d.m.Y。 我想获取两个日期之间的记录。

我正在尝试使用此代码:

$start = '10.09.2016';
$end = '20.10.2018';

$company->records()->whereBetween('exp_date', [$start, $end])->get();

【问题讨论】:

标签: laravel laravel-5 laravel-5.1


【解决方案1】:

只需使用扩展原生 PHP DateTime 类的carbon package。

示例 1:数据库列类型设置为 date 或 dateTime $start = '10.09.2016'; $end = '20.10.2018';

$start = Carbon::createFromFormat('d-m-Y',  $start)->toDateTimeString(); 
$end = Carbon::createFromFormat('d-m-Y',  $end)->toDateTimeString();

然后创建查询

$company = Records::where(function($q){
    $q->where('exp_date', '<=',$start );
    $q->where('exp_date', '>', $end);

});

$company->get();

示例 2:数据库列类型设置为 varchar

在这里,您首先必须通过迁移来隐藏现有的表列。 在修改列之前,请务必将 doctrine/dbal 依赖项添加到您的 composer.json 文件中。

php artisan make:migration update_exp_to_records_table --table=records

编辑迁移文件,在下面添加与您的表名相关的内容

Schema::table('records', function ($table) {
    $table->string('expire')->date()->change();
});

仅运行此特定迁移 然后在您的控制器函数中使用上面的示例 1。

【讨论】:

  • 但是数据库记录也应该是Date格式?
  • 是的,让我在使用 string/varchar 类型的列时更新它,等几分钟
【解决方案2】:

对于原始查询,您应该使用如下内容:

SELECT * FROM table_name 
WHERE UNIX_TIMESTAMP(col_name) > UNIX_TIMESTAMP(:start) 
  AND UNIX_TIMESTAMP(col_name) < UNIX_TIMESTAMP(:end)

您不必在 PHP 中将 UNIX_TIMESTAMP() 用于 $start 和 $end 值,只需 strtotime()。

注意:如果 MySQL 没有将字符串输入到 unix 时间戳中,可能需要使用函数 CAST()。

文档:UNIX_TIMESTAMP() in MySQL,strtotime() in PHP

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-06-03
    • 1970-01-01
    • 1970-01-01
    • 2011-01-15
    • 1970-01-01
    • 2015-12-17
    • 1970-01-01
    相关资源
    最近更新 更多