我有一个过滤器。
筛选器包含三个字段。 Call_Date_From
、Call_Date_Till
、Telephone
。
所以我需要从LEADS
(潜在客户模型)表中进行选择所有适合过滤器的行。
在原始的 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 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();
}