当前位置: 首页 > 工具软件 > yii2-wschat > 使用案例 >

Yii2 调用数据简单显示(很好懂的实例)

籍英叡
2023-12-01

数据模型层
models/ZsDynasty.php

[php]  view plain  copy
  1. <?php  
  2. namespace app\models;  
  3.   
  4.   
  5. use yii\db\ActiveRecord;  
  6.   
  7.   
  8. class ZsDynasty extends ActiveRecord  
  9. {  
  10. }  
ZsDynasty 对应数据库表 zs_dynasty

控制器
Controller/TestController.php

[php]  view plain  copy
  1. <?php  
  2.   
  3. namespace app\controllers;  
  4.   
  5. use yii\web\Controller;  
  6. use yii\data\Pagination;//分页  
  7. use yii\data\ActiveDataProvider;//活动记录  
  8. use app\models\ZsDynasty;//自定义数据模型  
  9.   
  10. class TestController extends Controller  
  11. {  
  12.     public function actionIndex()  
  13.     {  
  14.         $query = ZsDynasty::find();  
  15.   
  16.   
  17.         $pagination = new Pagination([  
  18.             'defaultPageSize' => 15,  
  19.             'totalCount' => $query->count(),  
  20.         ]);  
  21.   
  22.   
  23.         $dynastys = $query->orderBy('dyn_id')  
  24.             ->offset($pagination->offset)  
  25.             ->limit($pagination->limit)  
  26.             ->all();  
  27.   
  28.   
  29.         return $this->render('index', [  
  30.             'dynastys' => $dynastys,  
  31.             'pagination' => $pagination,  
  32.         ]);  
  33.     }  
  34. }  

对应网址 index.php?r=test/index

视图
views\test\index.php
[php]  view plain  copy
  1. <?php  
  2. use yii\helpers\Html;  
  3. use yii\widgets\LinkPager;  
  4.   
  5. $this->title = '朝代';  
  6. $this->params['breadcrumbs'][] = $this->title;  
  7. ?>  
  8. <h1>朝代</h1>  
  9. <ul>  
  10. <?php foreach ($dynastys as $dynasty): ?>  
  11.     <li>  
  12.         <?= Html::encode("{$dynasty->dyn_name} ({$dynasty->dyn_id})") ?>:  
  13.     </li>  
  14. <?php endforeach; ?>  
  15. </ul>  
  16.   
  17. <?= LinkPager::widget(['pagination' => $pagination]) ?>  
 类似资料: