2017-05-22 37 views

回答

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(); 
+0

感谢您的详细回答,相当有用 –

+0

此查询打印此。 select * from'questions' where'status' = 1 and'start_time'> ='2017-05-22 10:03:48'and'end_time' <='2017-05-22 10:03:48'order通过'id' asc,它返回null,即使值在这个范围之间退出 –

+0

@KhiradBanu我的意思是检查我更新的答案。雄辩的查询之前有错误的日期比较。更改您的代码以使用我的答案中的新代码。正确的检查是'start_time <='2017-05-22 10:03:48'和end_time> ='2017-05-22 10:03:48''这在您的查询中是错误的。 – Sandeesh

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

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

+0

用途,其中( '状态', '=',1)代替哪里('状态',1)。 - > Laravel 5.4需要它。 –

+0

你也可以考虑定义一个[Eloquent Model](https://laravel.com/docs/5.4/eloquent#defining-models)。例如,在这里,你的表'tble'的模型将是'Tble',然后你可以替换DB :: table('tble'):: Tble :: – ochhii

+1

@PatrykWoziński你仍然可以传递2个参数到where子句Laravel 5.4会假定运算符是'='。 –

0

尝试此

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

这将打印。 从'questions'选出*,其中'status' = 1,'2017-05-22 10:08:16'在start_time和end_time之间的顺序通过'id' asc limit 1,这是错误的。 –