2015-06-14 49 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请求,只有在调用方法时才会执行单个查询 - >在这个例子中分页。 –

相关问题