Yii-pagination
Yii-ページネーション
1つのページに表示するにはデータが多すぎる場合は、複数のページに表示する必要があります。 これはページネーションとも呼ばれます。
ページネーションの動作を示すには、データが必要です。
DBの準備
- ステップ1 *-新しいデータベースを作成します。 データベースは、次の2つの方法で準備できます。
- ターミナルで_mysql -u root -p_を実行します
- _CREATE DATABASE helloworld CHARACTER SET utf8 COLLATE utf8_general_ci; _を介して新しいデータベースを作成します
ステップ2 *- *config/db.php ファイルでデータベース接続を設定します。 次の構成は、現在使用されているシステム用です。
<?php
return [
'class' => 'yii\db\Connection',
'dsn' => 'mysql:host = localhost;dbname = helloworld',
'username' => 'vladimir',
'password' => '12345',
'charset' => 'utf8',
];
?>
ステップ3 *-ルートフォルダー内で./yii migrate/create test_table *を実行します。 このコマンドは、DBを管理するためのデータベース移行を作成します。 移行ファイルは、プロジェクトルートの *migrations フォルダーに表示されます。
ステップ4 *-この方法で移行ファイル(この場合は *m160106_163154_test_table.php )を変更します。
<?php
use yii\db\Schema;
use yii\db\Migration;
class m160106_163154_test_table extends Migration {
public function safeUp() {
$this->createTable("user", [
"id" => Schema::TYPE_PK,
"name" => Schema::TYPE_STRING,
"email" => Schema::TYPE_STRING,
]);
$this->batchInsert("user", ["name", "email"], [
["User1", "[email protected]"],
["User2", "[email protected]"],
["User3", "[email protected]"],
["User4", "[email protected]"],
["User5", "[email protected]"],
["User6", "[email protected]"],
["User7", "[email protected]"],
["User8", "[email protected]"],
["User9", "[email protected]"],
["User10", "[email protected]"],
["User11", "[email protected]"],
]);
}
public function safeDown() {
$this->dropTable('user');
}
}
?>
上記の移行では、id、name、およびemailのフィールドを持つ user テーブルが作成されます。 また、いくつかのデモユーザーを追加します。
- ステップ5 *-プロジェクトのルート内で./yii migrate *を実行して、データベースに移行を適用します。
ステップ6 *-次に、 *user テーブルのモデルを作成する必要があります。 簡単にするために、 Gii コード生成ツールを使用します。 この url:http://localhost:8080/index.php?r = gii を開きます。 次に、「Model generator」ヘッダーの下にある「Start」ボタンをクリックします。 テーブル名(「ユーザー」)とモデルクラス(「MyUser」)を入力し、「プレビュー」ボタンをクリックして、最後に「生成」ボタンをクリックします。
*MyUser* モデルがモデルディレクトリに表示されます。
アクションのページネーション
ステップ1 *- *actionPagination メソッドを SiteController に追加します。
public function actionPagination() {
//preparing the query
$query = MyUser::find();
//get the total number of users
$count = $query->count();
//creating the pagination object
$pagination = new Pagination(['totalCount' => $count, 'defaultPageSize' => 10]);
//limit the query using the pagination and retrieve the users
$models = $query->offset($pagination->offset)
->limit($pagination->limit)
->all();
return $this->render('pagination', [
'models' => $models,
'pagination' => $pagination,
]);
}
ステップ2 *- *views/site フォルダー内に pagination.php というビューファイルを作成します。
<?php
use yii\widgets\LinkPager;
?>
<?php foreach ($models as $model): ?>
<?= $model->id; ?>
<?= $model->name; ?>
<?= $model->email; ?>
<br/>
<?php endforeach; ?>
<?php
//display pagination
echo LinkPager::widget([
'pagination' => $pagination,
]);
?>
今、Webブラウザを介してローカルホスト http://localhost:8080/index.php?r = site/pagination にアクセスすると、ページネーションウィジェットが表示されます-