【发布时间】:2017-10-21 20:24:22
【问题描述】:
这是我的原始查询。
DB::raw("SELECT * FROM tble WHERE status=1 and now() BETWEEN start_time 和 end_time ORDER BY id DESC LIMIT 1")
如何将其转换为 Laravel Eloquent?
【问题讨论】:
这是我的原始查询。
DB::raw("SELECT * FROM tble WHERE status=1 and now() BETWEEN start_time 和 end_time ORDER BY id DESC LIMIT 1")
如何将其转换为 Laravel Eloquent?
【问题讨论】:
DB::table('tble')::where('status',1)
->where('start_time', '<=', Carbon::now())
->where('end_time', '>=', Carbon::now())
->orderBy('id')
->first();
您可以使用简单的日期处理包Carbon 来实现这一点。
【讨论】:
=。
<= 和 >=,因为 BETWEEN 包含范围。 OP 可能必须注意的一个问题是时区问题 - 特别是如果应用程序中使用的时间是一致的。
first() 或take(1)->get(),因为作者希望将结果限制为 1 行
为表app/Table.php创建模型
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Table extends Model
{
protected $table = 'tble';
}
逻辑
$now = \Carbon\Carbon::now();
$result = \App\Table::where('status', 1)
->where('start_time', '<=', $now)
->where('end_time', '>=', $now)
->orderBy('id')
->first();
【讨论】:
questions where status = 1 and start_time >= '2017-05-22 10:03:48' and end_time id asc,它返回null,即使值在这个范围内退出
start_time <= '2017-05-22 10:03:48' and end_time >= '2017-05-22 10:03:48' ,这在您的查询中是错误的。
试试这个
DB::table('tble')::where('status',1)
->whereBetween(Carbon::now(), ['start_time', 'end_time'])
->orderBy('id')
->first();
【讨论】:
questions where status = 1 and 2017-05-22 10:08:16 between start_time and end_time order by id asc limit 1,这是错误的。