2015-06-14 32 views
0

我有一個過濾器。如何正確地從數據庫中根據過濾器中的數據選擇數據?

過濾器包含三個字段。 Call_Date_FromCall_Date_TillTelephone

所以我需要從LEADS(Lead Model)表中選擇適合濾鏡的所有行。

在原PHP + MySQL的我會寫這樣的事:

$sql = ' WHERE '; 
$post['call_date_from'] ? $sql .= ' `call_date` >= ' . $post['call_date_from']; 
$post['call_date_till'] ? $sql .= ' AND `call_date` <= ' . $post['call_date_till']; 
$post['telephone'] ? $sql .= ' AND `telephone` LIKE %' . $post['telephone'] . '%'; 

mysql: 'SELECT * FROM LEADS' . $sql; 

那麼,如何正確地做Laravel口才一樣嗎?

回答

0

這是如何使用Query Scope在Laravel Eloquent中進行過濾。

在型號

class Lead extends Model 
{ 
    public function scopeCallDateFrom($query, $date) 
    { 
     if ($date) { 
      return $query->where("call_date", ">=", $date); 
     } else{ 
      return $query; 
     } 
    } 

    public function scopeCallDateTill($query, $date) 
    { 
     if ($date) { 
      return $query->where("call_date", "<=", $date); 
     } else{ 
      return $query; 
     } 
    } 

    public function scopeTelephone($query, $telephone) 
    { 
     if ($telephone) { 
      return $query->where("telephone", "LIKE", "%$telephone%"); 
     } else{ 
      return $query; 
     } 
    } 
} 

在控制器

public index() 
{ 
     $posts = Lead::CallDateFrom(Input::get('call_date_from')) 
         ->CallDateTill(Input::get('call_date_till')) 
         ->Telephone(Input::get('telephone')) 
         ->orderBy('created_at', 'DESC') 
         ->paginate(); 
} 
+0

是不是太 「昂貴」 的要求分貝幾次? 在原始mysql中,我們可以通過單個查詢來完成:( –

+1

這並不昂貴,在每個查詢範圍中,它只是構建最終的SQL語句而不是db請求,只有在調用方法時纔會執行單個查詢 - >在這個例子中分頁。 –

相關問題