Php 如何根据Eloquent中的过滤器正确地从数据库中选择数据?
我有一个过滤器 过滤器包含三个字段<代码>从呼叫日期,Php 如何根据Eloquent中的过滤器正确地从数据库中选择数据?,php,mysql,laravel,eloquent,Php,Mysql,Laravel,Eloquent,我有一个过滤器 过滤器包含三个字段从呼叫日期,呼叫日期直到,电话 因此,我需要从Lead(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` &l
呼叫日期直到
,电话
因此,我需要从Lead
(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;
$sql='WHERE';
$post[“通话日期”]$sql.='`调用日期'>='$post[“通话日期”];
$post['call_date_till']吗$sql.='和'call_date`这是如何使用Laravel Elount进行过滤的
模型中
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;
}
}
}
多次请求db不是太“昂贵”了吗?在原始mysql中,我们可以通过单个查询来实现:(这并不昂贵。在每个查询范围中,它只是构建最终的SQL语句,而不是db请求。在本例中,当您调用方法->分页时,只会执行单个查询。
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();
}