当我想在我的分页中添加 where 子句时,我遇到了问题:
这很好用:
$builder = User::orderBy(
$criteria->getOrderBy(),
$criteria->getOrderWay()
)
->paginate(
$criteria->getPerPage(),
array('*'),
'',
$criteria->getPage()
);
return $builder;
如果我想添加以下条件,如果我执行以下操作(它适用于btw):
$builder = User::orderBy(
$criteria->getOrderBy(),
$criteria->getOrderWay()
)->where(array(array('state','=',0)))
->paginate(
$criteria->getPerPage(),
array('*'),
'',
$criteria->getPage()
);
return $builder;
但如果我想在没有链接的情况下这样做:
$builder = User::orderBy(
$criteria->getOrderBy(),
$criteria->getOrderWay()
);
$builder->where(array(array('state','=',0)));
$builder->paginate(
$criteria->getPerPage(),
array('*'),
'',
$criteria->getPage()
);
return $builder;
我得到以下异常:
调用未定义的方法Illuminate \ Database \ Query \ Builder :: lastPage()
所以分页不适用,但为什么呢?
如何在不重复代码的情况下添加where子句?
$arrClauses = /** example **/;
if(empty($arrClauses)) {
$builder = User::orderBy(
$criteria->getOrderBy(),
$criteria->getOrderWay()
)
->paginate(
$criteria->getPerPage(),
array('*'),
'',
$criteria->getPage()
);
return $builder;
} else {
$builder = User::orderBy(
$criteria->getOrderBy(),
$criteria->getOrderWay()
)->where($arrClauses)
->paginate(
$criteria->getPerPage(),
array('*'),
'',
$criteria->getPage()
);
return $builder;
}
答案 0 :(得分:2)
您收到错误是因为您正在返回Query Builder实例而不是LengthAwarePaginator
实例。这样做是为了让它发挥作用:
$builder = User::orderBy(
$criteria->getOrderBy(),
$criteria->getOrderWay()
);
$builder = $builder->where(array(array('state','=',0)));
$builder = $builder->paginate(
$criteria->getPerPage(),
array('*'),
'',
$criteria->getPage()
);
return $builder;
答案 1 :(得分:1)
你的问题是你没有连接查询,这应该有效:
$arrClauses = /** Your clauses **/;
$builder = User::orderBy(
$criteria->getOrderBy(),
$criteria->getOrderWay()
);
if(!empty($arrClauses)) {
$builder = $builder->where($arrClauses);
}
$builder = $builder->paginate(
$criteria->getPerPage(),
array('*'),
'',
$criteria->getPage()
);
return $builder;
答案 2 :(得分:0)
希望这会对你有所帮助
$builder = User::orderBy(
$criteria->getOrderBy(),
$criteria->getOrderWay()
);
if(!empty($arrClauses))
$builder = $builder->where($arrClauses);
$builder->paginate(
$criteria->getPerPage(),
array('*'),
'',
$criteria->getPage()
);
return $builder;