大部分來源於 https://getyii.com/topic/47#comment24php
獲取當前Controller name和action name(在控制器裏面使用)
echo $this->id; echo $this->action->id;
控制器獲取當前模塊
$this->module->id
不生成label標籤web
// ActiveForm類 $form->field($model, '字段名')->passwordInput(['maxlength' => true])->label(false) ?>
Yii2 獲取接口傳過來的 JSON 數據:
Yii::$app->request->rawBody;
防止 SQL 和 Script 注入:
use yii\helpers\Html; use yii\helpers\HtmlPurifier; echo Html::encode($view_hello_str) //能夠原樣顯示<script></script>代碼 echo HtmlPurifier::process($view_hello_str) //能夠過濾掉<script></script>代碼
大於、小於條件查詢
// 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]); //可選傳參 $dataProvider->query->andFilterWhere(['id'=>isset($id)?$id:null]);
有兩種方式獲取查詢出來的 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], ]; }
SQL is not null條件查詢
// ['not' => ['attribute' => null]]
//['ISNULL(`attribute`)'=>true] $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; }
執行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/頭像路徑 } }
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.'],
Model多個字段一條規則不一樣提示數據庫
[['name', 'email', 'subject', 'body'], 'required','message'=>'{attribute} 必須'],
標量查詢 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 的值
表單驗證,去除首尾空格:
public function rules() { return [[title', 'content'],'trim']]; }
單獨爲某個Action關閉 Csrf 驗證
新建一個Behavior
use Yii; use yii\base\Behavior; use yii\web\Controller; class NoCsrf extends Behavior { public $actions = []; public $controller; public function events() { return [Controller::EVENT_BEFORE_ACTION => 'beforeAction']; } public function beforeAction($event) { $action = $event->action->id; if (in_array($action, $this->actions)) { $this->controller->enableCsrfValidation = false; } } }
而後在Controller中添加Behavior
public function behaviors() { return [ 'csrf' => [ 'class' => NoCsrf::className(), 'controller' => $this, 'actions' => [ 'action - name' ] ] ]; }
LIKE 查詢 單邊加 %
['like', 'name', 'tester'] 會生成 name LIKE ' % tester % '。 ['like', 'name', ' % tester', false] => name LIKE ' % tester' $query = User::find()->where(['LIKE', 'name', $id . ' % ', false]);
SQL 隨機抽取十名幸運用戶
$query = new Query; $query->select('ID, City,State,StudentName') ->from('student') ->where(['IsActive' => 1]) ->andWhere(['not', ['State' => null]]) ->orderBy(['rand()' => SORT_DESC]) ->limit(10);
關於事務:
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; }
批量插入數據
第一種方法 $model = new User(); foreach ($data as $attributes) { $_model = clone $model; $_model->setAttributes($attributes); $_model->save(); } 第二種方法 $model = new User(); foreach ($data as $attributes) { $model->isNewRecord = true; $model->setAttributes($attributes); $model->save() && $model->id = 0; }
URL操做數組
獲取url中的host信息 Yii::$app->request->getHostInfo() 獲取url中的路徑信息(不包含host和參數): Yii::$app->request->getPathInfo() 獲取不包含host信息的url(含參數): # /public/index.php?r=news&id=1 Yii::$app->request->url 或者 Yii::$app->request->requestUri 只想獲取url中的參數部分 # r=news&id=1 Yii::$app->getRequest()->queryString; 獲取某個參數的值,好比id Yii::$app->getRequest()->getQuery('id'); //get parameter 'id' 獲取(除域名外的)首頁地址 # /public/index.php Yii::$app->user->returnUrl; 獲取Referer Yii::$app->request->headers['Referer'] 或者 Yii::$app->getRequest()->getReferrer()