【问题标题】:Yii2 and php-generators (yield) with mysqlYii2 和 php-generators (yield) 与 mysql
【发布时间】:2016-07-31 20:46:24
【问题描述】:

我有这样行的 mysql 表“Flats”

-----------------------
id | created    | rooms
-----------------------
1  | 2016-07-21 | 2
2  | 2016-07-20 | 1
3  | 2016-07-20 | 1
4  | 2016-07-19 | 2
5  | 2016-07-18 | 2
6  | 2016-07-18 | 1
7  | 2016-07-17 | 2
8  | 2016-07-17 | 1
-----------------------

我需要按日期 (DESC) 排序选择 3 套 2 室公寓和 4 套 1 室公寓。选定的信息(3 和 4 个单位)将在第一个站点的页面上。然后我需要选择下一个信息(接下来的 3 和 4 个单位)。

1)- 我如何在 yii2 中使用不分页和不使用 mysql 偏移,而是使用 php-generators (yield) 来做到这一点。 2)- 更好的方法是什么- mysql offset 或 php-yield 。

【问题讨论】:

  • 我什至不知道如何在 Yii2 中启动这段代码——如何结合活动查询和生成器

标签: mysql pagination yii2 generator yield


【解决方案1】:

我认为这种方法没有任何好处。为什么要重新发明轮子,尤其是当您选择使用框架并且它已经提供了分页组件时?

您可以在Pagination 文章中了解常见的分页。示例:

use yii\data\Pagination;

// build a DB query to get all articles with status = 1
$query = Article::find()->where(['status' => 1]);

// get the total number of articles (but do not fetch the article data yet)
$count = $query->count();

// create a pagination object with the total count
$pagination = new Pagination(['totalCount' => $count]);

// limit the query using the pagination and retrieve the articles
$articles = $query->offset($pagination->offset)
    ->limit($pagination->limit)
    ->all();

页面链接显示为yii\widgets\LinkPager 小部件:

use yii\widgets\LinkPager;

echo LinkPager::widget([
    'pagination' => $pagination,
]);

还有yii\data\Pagination组件的一些细节。

了解框架功能并使用它。例如,当使用ActiveDataProviderGridView 小部件时,分页已经内置,因此您只需配置它以满足您的需求(每页项目等),而不关心内部实现的细节(偏移量, ETC。)。但是,如果您了解它的工作原理,显然会更好。

【讨论】:

    猜你喜欢
    • 2019-04-04
    • 2014-06-26
    • 1970-01-01
    • 2014-12-28
    • 2015-02-21
    • 1970-01-01
    • 2013-07-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多