2017-05-22 38 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,這是錯誤的。 –