Yii分页的使用

1、Controller中action

<?
use yii\data\Pagination;
....
public function actionList()
{
  $query = Article::find()->where(['status' => 1]);
  $countQuery = clone $query;
  $pages = new Pagination(['totalCount' => $countQuery->count()]);
  $models = $query->offset($pages->offset)
      ->limit($pages->limit)
      ->all();
  return $this->render('index', [
      'models' => $models,
      'pages' => $pages,
   ]);
}

默认分页的数量是20,你可以设置pageSize为你想要的

$pages = new Pagination([ 
    'totalCount' => $totalCount, 
    'pageSize' => 5, 
]);

继续阅读Yii分页的使用

Yii2数据库操作

1、常用查询

// WHERE admin_id >= 10 LIMIT 0,10
 User::find()->select('*')->where(['>=', 'admin_id', 10])->offset(0)->limit(10)->all()
// SELECT `id`, (SELECT COUNT(*) FROM `user`) AS `count` FROM `post`   
 $subQuery = (new Query())->select('COUNT(*)')->from('user');    
 $query = (new Query())->select(['id', 'count' => $subQuery])->from('post');
// SELECT DISTINCT `user_id` ... 
 User::find()->select('user_id')->distinct();

2、更新操作

//update();
//runValidation boolen 是否通过validate()校验字段 默认为true 
//attributeNames array 需要更新的字段 
$model->update($runValidation , $attributeNames);  

//updateAll();
//update customer set status = 1 where status = 2
Customer::updateAll(['status' => 1], 'status = 2'); 

//update customer set status = 1 where status = 2 and uid = 1;
Customer::updateAll(['status' => 1], ['status'=> '2','uid'=>'1']);

//updateAllCounters()在数据库值的基础上进行操作

Customer::updateAllCounters(['age' => 1]); //增加所有年龄字段加1


继续阅读Yii2数据库操作

Yii实用技巧

1、如何禁止加载Yii自带的jQuery、bootstarp、bootstarp插件

//禁止加载jquery.js
'assetManager' => [
    'bundles' => [
        'yii\web\JqueryAsset' => [
            'js'=>[]
        ],
    ],
],
//禁止加载bootstarp.js、bootstarp.css
'assetManager' => [
    'bundles' => [
        'yii\bootstrap\BootstrapPluginAsset' => [
            'js'=>[]
        ],
    ],
],
'assetManager' => [
    'bundles' => [
        'yii\bootstrap\BootstrapAsset' => [
            'css' => [],
        ],
    ],
],

添加在应用的配置文件中的components中。 继续阅读Yii实用技巧