紫悦博客

不进则退,退一步万丈悬崖!

0%

Yii2 小贴士集合

表单提交失败调试代码

1
echo array_values($model->getFirstErrors())[0];exit;

获取当前Controller name和action name(在控制器里面使用)

1
2
echo $this->id;
echo $this->action->id;

控制器获取当前模块

1
$this->module->id

use yii\log\Logger;

1
2
use yii\log\Logger;
\Yii::getLogger()->log('User has been created', Logger::LEVEL_INFO);

不生成label标签

1
2
3
4
// ActiveForm类
$form->field($model, '字段名')->passwordInput(['maxlength' => true])->label(false) ?>
// HTML类
Html::activeInput($type,$model,'字段名')

Yii2 获取接口传过来的 JSON 数据:

1
Yii::$app->request->rawBody;

防止 SQL 和 Script 注入:

1
2
3
4
5
use yii\helpers\Html;
use yii\helpers\HtmlPurifier;

echo Html::encode($view_hello_str) //可以原样显示<script></script>代码
echo HtmlPurifier::process($view_hello_str) //可以过滤掉<script></script>代码

大于、小于条件查询

1
2
3
4
5
// SELECT * FROM `order` WHERE `subtotal` > 200 ORDER BY `id`
$orders = $customer->getOrders()
->where(['>', 'subtotal', 200])
->orderBy('id')
->all();

搜索的时候添加条件筛选

1
2
3
$dataProvider = $searchModel->search(Yii::$app->request->queryParams);
// $dataProvider->query->andWhere(['pid' => 0]);
$dataProvider->query->andWhere(['>', 'pid', 0]);

有两种方式获取查询出来的 name 为数组的集合 [name1, name2, name3]:

方式一:

1
return \yii\helpers\ArrayHelper::getColumn(User::find()->all(), 'name');

方式二:

1
return User::find()->select('name')->asArray()->column();

打印数据

1
2
3
4
5
6
7
8
// 引用命名空间
use yii\helpers\VarDumper;

// 使用
VarDumper::dump($var);

// 使用2 第二个参数是数组的深度 第三个参数是是否显示代码高亮(默认不显示)
VarDumper::dump($var, 10 ,true);die;

表单验证,只要需要一个参数

1
2
3
4
5
6
7
8
9
10
public function rules()
{
return [
[['card_id', 'card_code'], function ($attribute, $param) {//至少要一个
if (empty($this->card_code) && empty($this->card_id)) {
$this->addError($attribute, 'card_id/card_code至少要填一个');
}
}, 'skipOnEmpty' => false],
];
}

where 多个查询条件示例

1
User::find()->where(['and', ['xxx' => 0, 'yyy' => 2], ['>', 'zzz', $time]]);

获取post数据

1
2
$post = Yii::$app->request->post();
$id = $post['id'];

查找 auth_times 表 type=1 并且 不存在 auth_item 表里面的数据

查找 auth_timestype=1 并且 不存在 auth_item 表里面的数据

1
2
3
4
5
6
7
8
9
// AuthItem.php 关键是 onCondition 方法
public function getAuthTimes()
{
return $this->hasOne(AuthTimes::className(), ['name' => 'name', ])->onCondition([AuthTimes::tableName() . '.type' => 1]);
}

// AuthTimes.php 文件
// ......
AuthItem::find()->joinWith('authTimes')->where([self::tableName() . '.name' => null])->all();

生成SQL:

1
SELECT `auth_item`.* FROM `auth_item` LEFT JOIN `auth_times` ON `auth_item`.`name` = `auth_times`.`name` AND `auth_times`.`type` = 1 WHERE `auth_times`.`name` IS NULL

SQL is not null条件查询

1
2
3
4
5
6
7
8
9
10
// ['not' => ['attribute' => null]]

$query = new Query;
$query->select('ID, City,State,StudentName')
->from('student')
->where(['IsActive' => 1])
->andWhere(['not', ['City' => null]])
->andWhere(['not', ['State' => null]])
->orderBy(['rand()' => SORT_DESC])
->limit(10);

校验 point_template_id 在 PointTemplate 是否存在

1
2
3
4
5
6
7
8
9
10
11
12
public function rules()
{
return [
...
[['point_template_id'], 'exist',
'targetClass' => PointTemplate::className(),
'targetAttribute' => 'id',
'message' => '此{attribute}不存在。'
],
...
];
}

Yii给必填项加星

1
2
3
4
div.required label:after {
content: " *";
color: red;
}

view里面获取当前action

1
var_dump(Yii::$app->controller->action->id);

关于事务

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
Yii::$app->db->transaction(function() {
$order = new Order($customer);
$order->save();
$order->addItems($items);
});

// 这相当于下列冗长的代码:

$transaction = Yii::$app->db->beginTransaction();
try {
$order = new Order($customer);
$order->save();
$order->addItems($items);
$transaction->commit();
} catch (\Exception $e) {
$transaction->rollBack();
throw $e;
}

restful 获取 GET 和 POST 过来的数据(得到结果是数组)

1
2
3
4
5
// post
Yii::$app->request->bodyParams

// get
Yii::$app->request->queryParams;

获取GET数据

1
$server_id = Yii::$app->getRequest()->get('server_id');

查询的时候 where 的 OR 和 AND 一起用

1
2
3
4
5
Topic::updateAll(
['last_comment_time' => new Expression('created_at')],
// ['or', ['type' => Topic::TYPE, 'last_comment_username' => ''], ['type' => Topic::TYPE, 'last_comment_username' => null]]
['and', ['type' => Topic::TYPE], ['or', ['last_comment_username' => ''], ['last_comment_username' => null]]]
);

### 嵌套查询,groupBy 分组之后排序功能

1
2
3
4
5
$subQuery = new Query();
$subQuery->from(PostComment::tableName())->where(['status' => PostComment::STATUS_ACTIVE])->orderBy(['created_at' => SORT_DESC]);
$comment = PostComment::find()->from(['tmpA' => $subQuery])
->groupBy('post_id')
->all();

生成的语句是

1
SELECT * FROM (SELECT * FROM `post_comment` WHERE `status`=1 ORDER BY `created_at` DESC) `tmpA` GROUP BY `post_id`

Model 获取当前 module id

1
Yii::$app->controller->module->id

一个控制器调用其他控制器action的方法

1
2
3
Yii::$app->runAction('new_controller/new_action', $params);
// 或者
return (new SecondController('second', Yii::$app->module))->runAction('index', $data);

IP 白名单

1
2
3
4
$config['modules']['debug'] = [
'class' => 'yii\debug\Module',
'allowedIPs' => ['127.0.0.1', '::1', '192.168.0.*', '192.168.33.1'],
];

点击下载文件 action

1
2
3
4
5
6
7
8
9
10
public function actionDownload($id)
{
$model = $this->findModel($id);

if ($model) {
// do something
}
return \Yii::$app->response->setDownloadHeaders($model->downurl);

}

发送邮件 config/config.php中的components配置

1
2
3
4
5
6
7
8
9
10
11
12
'mailer' => [
'class' => 'yii\swiftmailer\Mailer',
'useFileTransport' => false,
'transport' => [
'class' => 'Swift_SmtpTransport',
'host' => 'smtp.gmail.com',
'username' => '[email protected]',
'password' => 'password12345678',
'port' => 587,//or 25/587
'encryption' => 'tls',//tls or ssl
]
],

使用

1
2
3
4
5
6
Yii::$app->mailer->compose()
->setFrom(['[email protected]' => Yii::$app->name])
->setTo('[email protected]')
->setSubject('test subject')
->setTextBody('test body')
->send();

修改登陆状态超时时间(到期后自动退出登陆) config/web.php中的components

1
2
3
4
5
6
7
'user' => [
'class'=>'yii\web\User',
'identityClass' => 'common\models\User',
'loginUrl'=>['/user/sign-in/login'],
'authTimeout' => 1800,//登陆有效时间
'as afterLogin' => 'common\behaviors\LoginTimestampBehavior'
],

修改返回的数据格式(详见Response::FORMAT_XXXX)

1
2
3
4
5
6
7
8
9
10
11
12
13
$result = array('code' => $code, 'msg' => $msg, 'data' => $data);
$callback = Yii::$app->request->get('callback',null);

$format = $callback ? Response::FORMAT_JSONP : Response::FORMAT_JSON;
Yii::$app->response->format = $format;

if($callback){
return array(
'callback' => $callback,
'data' => $result
);
}
return $result;

执行SQL查询并缓存结果

1
2
3
4
$styleId = Yii::$app->request->get('style');
$collection = Yii::$app->db->cache(function($db) use($styleId){
return Collection::findOne(['style_id'=>$styleId]);
}, self::SECONDS_IN_MINITUE * 10);

用户头像加域名

场景: 数据库有user 表有个avatar_path 字段用来保存用户头像路径

需求: 头像url需要通过域名http://b.com/作为基本url

目标: 提高代码复用

此处http://b.com/可以做成一个配置
示例:

User.php

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
class User extends \yii\db\ActiveRecord
{
...
public function extraFields()
{
$fields = parent::extraFields();

$fields['avatar_url'] = function () {
return empty($this->avatar_path) ? '可以设置一个默认的头像地址' : 'http://b.com/' . $this->avatar_path;
};

return $fields;
}
...
}

ExampleController.php

1
2
3
4
5
6
7
8
9
10
class ExampleController extends \yii\web\Controller
{
public function actionIndex()
{
$userModel = User::find()->one();
$userData = $userModel->toArray([], ['avatar_url']);

echo $userData['avatar_url']; // 输出内容: http://b.com/头像路径
}
}

避免select里面的子查询被识别成字段

1
2
3
4
5
6
//避免select里面的子查询被识别成字段
$quert = User::find()
->select([
new Expression('count(*) as count , count(distinct mobile) as mnumber')
])->asArray()
->all();

like 查询

1
2
$query = User::find()
->where(['LIKE', 'name', $id.'%', false]);

来源:http://www.getyii.com/topic/47