Yii-排序

当显示大量数据时,我们经常需要对数据进行排序。Yii使用yii \ data \ Sort对象来表示排序模式。

为了显示排序,我们需要数据。

准备数据库

步骤1-创建一个新的数据库。可以通过以下两种方式准备数据库。

  • 在终端中运行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 migration / create test_table。此命令将创建数据库迁移以管理我们的数据库。迁移文件应出现在项目根目录的迁移文件夹中。

步骤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", "user1@gmail.com"],
            ["User2", "user2@gmail.com"],
            ["User3", "user3@gmail.com"],
            ["User4", "user4@gmail.com"],
            ["User5", "user5@gmail.com"],
            ["User6", "user6@gmail.com"],
            ["User7", "user7@gmail.com"],
            ["User8", "user8@gmail.com"],
            ["User9", "user9@gmail.com"],
            ["User10", "user10@gmail.com"],
            ["User11", "user11@gmail.com"],
         ]);
      }
      public function safeDown() {
         $this->dropTable('user');
      }
   }
?>

上面的迁移将创建一个用户表,其中包含以下字段:ID,名称和电子邮件。它还增加了一些演示用户。

步骤5-在项目根目录内运行./yii migration,以将迁移应用于数据库。

步骤6-现在,我们需要为我们的用户表创建一个模型。为了简单起见,我们将使用Gii代码生成工具。打开以下网址:http:// localhost:8080 / index.php?r = gii。然后,单击“模型生成器”标题下的“开始”按钮。填写表名称(“用户”)和模型类(“ MyUser”),单击“预览”按钮,最后单击“生成”按钮。

Yii-排序

MyUser模型应出现在models目录中。

进行排序

步骤1-actionSorting方法添加到SiteController

public function actionSorting() {
   //declaring the sort object
   $sort = new Sort([
      'attributes' => ['id', 'name', 'email'], 
   ]);
   //retrieving all users
   $models = MyUser::find()
      ->orderBy($sort->orders)
      ->all();
   return $this->render('sorting', [
      'models' => $models,
      'sort' => $sort,
   ]);
}

步骤2-在views / site文件夹创建一个名为sortingView文件。

<?php
   // display links leading to sort actions
   echo $sort->link('id') . ' | ' . $sort->link('name') . ' | ' . $sort->link('email');
?><br/>
<?php foreach ($models as $model): ?>
   <?= $model->id; ?>
   <?= $model->name; ?>
   <?= $model->email; ?>
   <br/>
<?php endforeach; ?>

步骤3-现在,如果您在Web浏览器中键入http:// localhost:8080 / index.php?r = site / sorting,您可以看到ID,名称和电子邮件字段是可排序的,如下图所示。

Yii-排序

作者:terry,如若转载,请注明出处:https://www.web176.com/yii/474.html

(0)
打赏 支付宝 支付宝 微信 微信
terryterry
上一篇 2020年10月26日 下午3:56
下一篇 2020年10月26日 下午4:02

相关推荐

发表回复

您的电子邮箱地址不会被公开。 必填项已用 * 标注