首页 文章

如何将这个Raw查询转换成Laravel Eloquent方式?

提问于
浏览
0

这是我的原始查询 .

DB :: raw(“SELECT * FROM tble WHERE status = 1 and now()BETWEEN start_time和end_time ORDER BY id DESC LIMIT 1”)

如何将其转换为Laravel Eloquent?

3 回答

  • 0
    DB::table('tble')::where('status',1)
                     ->where('start_time', '<=', Carbon::now())
                     ->where('end_time', '>=', Carbon::now())
                     ->orderBy('id')
                     ->first();
    

    您可以使用简单的日期处理包Carbon来实现此目的 .

  • 2

    试试这个

    DB::table('tble')::where('status',1)
                          ->whereBetween(Carbon::now(), ['start_time', 'end_time'])
                          ->orderBy('id')
                          ->first();
    
  • 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();
    

相关问题