Yii2 的小贴士用法

 

 

表单提交失败调试代码

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

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

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

控制器获取当前模块

$this->module->id
 

写 log 日志

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

不生成label标签

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

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

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

防止 SQL 和 Script 注入:

use yii\helpers\Html;
use yii\helpers\HtmlPurifier; echo Html::encode($view_hello_str) //可以原样显示代码 echo HtmlPurifier::process($view_hello_str) //可以过滤掉代码 
 

大于、小于条件查询

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

搜索的时候添加条件筛选

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

事务的用法

$transaction = $connection->beginTransaction();
try {
    $connection->createCommand($sql1)->execute();
    $connection->createCommand($sql2)->execute();
    //.... other SQL executions
    $transaction->commit();
} catch (Exception $e) {
    $transaction->rollBack();
}
 

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

方式一:

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

方式二:

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

打印数据:

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

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

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 多个查询条件示例:

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

获取post数据

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

 

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

// 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:

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条件查询

// ['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 是否存在

public function rules() { return [ ... [['point_template_id'], 'exist', 'targetClass' => PointTemplate::className(), 'targetAttribute' => 'id', 'message' => '此{attribute}不存在。' ], ... ]; } 
 

Yii给必填项加星

div.required label:after {
    content: " *"; color: red; } 
 
 

关于事务:

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 过来的数据(得到结果是数组):

// post
Yii::$app->request->bodyParams

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

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

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 分组之后排序功能

$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(); 

生成的语句是

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

Model 获取当前 module id

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

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

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

IP 白名单

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

点击下载文件 action

public function actionDownload($id) { $model = $this->findModel($id); if ($model) { // do something } return \Yii::$app->response->setDownloadHeaders($model->downurl); } 
 

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

        '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 ] ], 

2.使用

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

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

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

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

	$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查询并缓存结果

	$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

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

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里面的子查询被识别成字段
$quert = User::find()
    ->select([
          new Expression('count(*) as count , count(distinct mobile) as mnumber')
     ])->asArray()
    ->all();
 

like 查询

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

Model 里面 rules 联合唯一规则

[['store_id', 'member_name'], 'unique', 'targetAttribute' => ['store_id', 'member_name'], 'message' => 'The combination of Store ID and Member Name has already been taken.'], 
 

如果要用 find_in_set 需要使用到 Expression 表达式:

User::find()
    ->where(new Expression('FIND_IN_SET(:status, status)')) ->addParams([':status' => 1]) ->all(); 
 

使用表达式实现计数器:

PackageCardSold::updateAll(
    $condition + ['consume_num' => new Expression('`consume_num` + 1'), 'last_consume_item' => $consumerCode->remark, 'updated_at' => time()], ['trade_no' => $consumerCode->trade_no] ); 
 

标量查询

Post::find()->select('title')->where(['user_id' => $userId])->scalar();

生成 SQL

SELECT `title` FROM `post` WHERE `user_id`=1

直接输出 title 的值。

如果 select('title') 不写的话,生成 SQL 是:

`SELECT * FROM `post` WHERE `user_id`=1` 

直接输出 id 的值

 

 

like 左查询:

Table::find()->where(['like', 'name', $_GET['q'] . '%', false]);

转载于:https://www.cnblogs.com/llxpbbs/articles/9496965.html

你可能感兴趣的:(php,数据库,json)