php - Laravel 5 添加条件子句查询

标签 php mysql laravel laravel-5

我是 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/

相关文章:

php - 在 PUT、PATCH、DELETE ... 请求中使用 php 读取 multipart/form-data 的原始请求正文

php - 如何获取每个用户的所有帖子?

php - 当我将 JSON 发送到 WEB 服务器时,发生错误 : org. json.JSONException:字符 3 处的输入结束

mysql - 如何使用 Java SprinBoot CrudRepository 在 MySQL 中插入/更新 JSON 列的行

PHP 表单不向 MySQL 发送数据

php - Laravel 中 AJAX POST 请求后出现 422 无法处理的实体错误

php - 如何制作字符串数组

php - Laravel 一对多关系查询绑定(bind)显示 null?

php - Laravel 6 和 Vue.js 使用 vue-router 和 axios 更新子组件的记录

php - 在 wordpress 中添加新的顶级菜单时,是否可以即时创建 CPT?