【问题标题】:How to convert this Raw query into Laravel Eloquent way?如何将此原始查询转换为 Laravel Eloquent 方式?
【发布时间】: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?

【问题讨论】:

    标签: laravel eloquent


    【解决方案1】:
    DB::table('tble')::where('status',1)
                     ->where('start_time', '<=', Carbon::now())
                     ->where('end_time', '>=', Carbon::now())
                     ->orderBy('id')
                     ->first();
    

    您可以使用简单的日期处理包Carbon 来实现这一点。

    【讨论】:

    • 使用 where('status', '=', 1) 代替 where('status', 1)。 -> Laravel 5.4 需要它。
    • 你也可以考虑定义一个Eloquent Model。例如在这里,您的表“tble”的模型将是“Tble”,然后您可以替换 DB::table('tble'):: for Tble::
    • @PatrykWoziński 您仍然可以将 2 个参数传递给 Laravel 5.4 中的 where 子句,它将假定运算符为 =
    • @ThunderBird,您可能需要考虑使用 &lt;=&gt;=,因为 BETWEEN 包含范围。 OP 可能必须注意的一个问题是时区问题 - 特别是如果应用程序中使用的时间是一致的。
    • @thunderbird 您应该更改日期检查,因为作者想检查当前时间是否在字段之间。其次,您应该添加first()take(1)-&gt;get(),因为作者希望将结果限制为 1 行
    【解决方案2】:

    为表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();
    

    【讨论】:

    • 谢谢你的详细回答,很有用
    • 这个查询打印了这个。 select * from questions where status = 1 and start_time >= '2017-05-22 10:03:48' and end_time id asc,它返回null,即使值在这个范围内退出
    • @KhiradBanu 我的意思是检查我更新的答案。雄辩的查询之前有错误的日期比较。更改您的代码以使用我的答案中的新代码。正确的检查是 start_time &lt;= '2017-05-22 10:03:48' and end_time &gt;= '2017-05-22 10:03:48' ,这在您的查询中是错误的。
    • 谢谢@Sandeesh
    【解决方案3】:

    试试这个

     DB::table('tble')::where('status',1)
                          ->whereBetween(Carbon::now(), ['start_time', 'end_time'])
                          ->orderBy('id')
                          ->first();
    

    【讨论】:

    • 这将打印出来。选择 * from questions where status = 1 and 2017-05-22 10:08:16 between start_time and end_time order by id asc limit 1,这是错误的。
    猜你喜欢
    • 2018-01-04
    • 2021-09-11
    • 2019-04-29
    • 2016-04-27
    • 2019-05-31
    • 2018-10-10
    • 2018-09-12
    • 2019-04-04
    • 2020-02-07
    相关资源
    最近更新 更多