【问题标题】:How to fix "Call to a member function offset() on array" erron in my yii2 project如何在我的 yii2 项目中修复“调用数组上的成员函数 offset()”错误
【发布时间】:2019-06-10 08:06:12
【问题描述】:

我想在我的博客页面中设置分页。在分页之前这个动作起作用。

    $data = [];
    $query = Blog::find()->where(['status'=>1])->multilingual()->orderBy(['id'=>SORT_DESC])->all();


   $count = count($query);


    $pagination = new Pagination(['totalCount' => $count]);

    // limit the query using the pagination and retrieve the articles
    $data['blog'] = $query->offset($pagination->offset)->limit($pagination->limit)->all();


    return $this->render('blog-list',['data'=>$data, 'pagination'=>$pagination]);

每当我设置 PageSize 时,问题还没有解决。

【问题讨论】:

    标签: php yii pagination yii2


    【解决方案1】:

    您遇到错误是因为$query 变量包含记录数组而不是查询对象。如果你想修改查询,你可以保留它。

    $query = Blog::find()->where(['status'=>1])->multilingual();
    
    $count = $query->count();
    $pagination = new Pagination(['totalCount' => $count]);
    
    // limit the query using the pagination and retrieve the articles
    $data['blog'] = $query->orderBy(['id'=>SORT_DESC])->offset($pagination->offset)->limit($pagination->limit)->all();
    
    
    return $this->render('blog-list',['data'=>$data, 'pagination'=>$pagination]);
    

    【讨论】:

      【解决方案2】:

      删除all()

      $query = Blog::find()->where(['status'=>1])->multilingual()->orderBy(['id'=>SORT_DESC]);
      
      $totalCount = clone $query;
      $pagination = new Pagination(['totalCount' => count($totalCount->all())]);
      

      【讨论】:

      • 这是一种糟糕的性能方式。 1. 代码有两个副本 Query 对象 2. count($totalCount->all()) - 从数据库中获取所有记录它给数据库带来了额外的工作量
      • @MaximFedorov 您可以编写单独的查询来为您提供总数。那里不需要all() 的记录。对于第一种情况,尝试运行您的示例并检查总数。使用至少 50 条记录以获得更好的结果。
      • 1.使用 GridView 的 ActiveDataProvider 不会从表中选择所有行来计算计数记录。它使用->count() 函数。您可以在 git 存储库中看到它github.com/yiisoft/yii2/blob/master/framework/data/…
      • 2. ActiveDataProvide 克隆了一个查询,但是为什么呢?如果您查看 git 存储库中的详细信息,您可以看到 ActiveDataProvider 在修改之前克隆了一个查询。这个事实是有道理的,因为查询对象是通过引用传递的,对用户查询的任何修改都是一种不好的做法,可能会产生一些问题。
      • @MaximFedorov 这就是我对 totalCount 的解释。 IMO,对 totalCount 使用单独的查询,这个答案是根据 OP 的问题而不是关于性能的。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-08-25
      • 2018-05-19
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多