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

数据模型层
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]) ?>  
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值