我是 Laravel 新手。我只想将查询分配给变量,然后根据需要附加约束。
这是 Controller :
public function index (Request $request)
{
$limit = 5;
$query_params = $request->query();
if(isset($query_params['limit'])){
$limit = $query_params['limit'];
}
//This chained query works.
$query = DB::table('users')->where('id', '>', '23')->paginate($limit);
//This one doesn't work
/*$query = DB::table('users');
$query->where('id', '>', '23');
$query->paginate($limit);*/
//also tried with @btl suggestion and with following code:
/*$query = DB::table('users')->where('id', '>', '23');
$query->paginate($limit);*/
return $query;
}
它引发了这个错误:
"message": "Object of class Illuminate\\Database\\Query\\Builder could not be converted to string",
"exception": "ErrorException",
"file": "/home/sms/laraveresources/vendor/symfony/http-foundation/Response.php",
"line": 399,
有什么想法可以实现吗?
我在官方文档上没有找到有关向查询添加条件子句的示例。
我终于成功了。我必须在一个变量中构建查询条件并将其添加到查询中,但在单独的变量中对其进行分页。以下代码有效。
public function index (Request $request)
{
$limit = 5;
$query_params = $request->query();
if(isset($query_params['limit'])){
$limit = $query_params['limit'];
}
$query = DB::table('users');
if(isset($query_params['sort'])){
$sort = $query_params['sort'];
$direction = 'ASC';
if(isset($query_params['direction'])){
$direction = $query_params['direction'];
}
$query->orderBy($sort, $direction);
}
$query2 = $query->paginate($limit);
return $query2;
}
提前致谢。
最佳答案
您需要分配 $query->where('id', '>', '23');
也到一个变量。 where
使用该子句返回模型实例,它由于未分配给变量而丢失。
尝试以下操作:
$query = DB::table('users');
$query = $query->where('id', '>', '23');
$query->paginate($limit);
关于php - Laravel 5 添加条件子句查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48362678/