Yii2一些方法技巧小记
表單驗(yàn)證
- 表單驗(yàn)證,兩個(gè)參數(shù)中至少需要一個(gè):
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 表單驗(yàn)證,去除首尾空格:
- 1
- 2
- 3
- 4
- 校驗(yàn) user_id 在User表中是否存在,并自定義錯(cuò)誤信息。
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- Model 里面 rules 聯(lián)合唯一規(guī)則
- 1
- 表單提交失敗獲取save()錯(cuò)誤信息調(diào)試代碼
- 1
- 2
- 單獨(dú)為某個(gè)Action關(guān)閉 Csrf 驗(yàn)證
新建一個(gè)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;}} }- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
然后在Controller中添加Behavior
public function behaviors() {return ['csrf' => ['class' => NoCsrf::className(),'controller' => $this,'actions' => ['action-name']]]; }- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
數(shù)據(jù)查詢
- where 多個(gè)查詢條件示例:
- 1
- 查詢的時(shí)候 where 的 OR 和 AND 一起用
- 1
- 2
- 3
- 4
- 5
- 嵌套查詢,groupBy 分組之后排序功能
- 1
- 2
- 3
- 4
- 5
- 6
生成的語句是
SELECT * FROM (SELECT * FROM `post_comment` WHERE `status`=1 ORDER BY `created_at` DESC) `tmpA` GROUP BY `post_id`- 1
- sql計(jì)算字段中相同值重復(fù)次數(shù),并排序*
- 1
- 2
- 3
- 4
- 5
- 避免select里面的子查詢被識(shí)別成字段
- 1
- 2
- 3
- 4
- 5
- LIKE 查詢 單邊加%
- 1
- 2
- 3
- 4
- 5
- 6
- SQL 隨機(jī)抽取十名幸運(yùn)用戶
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- yii2 多表聯(lián)查 where條件里 A表字段=B表字段怎么表示?
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- where條件中兩字段相加或相減
- 1
- 輸出查詢的sql語句
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
輸出語句:
SELECT `weibo`.* FROM `weibo` LEFT JOIN `account` ON `weibo`.`account_open_id` = `account`.`open_id` WHERE ((`is_forward`=0) AND (`status`=1) AND (`account_open_id` IN ('123456789', '987654321', '098765432', '234123455')) AND (`read_limit_time` IS NULL)) AND (`posted_at` BETWEEN 1474946053-`account`.`scrape_time`*60 AND 1474946053-`account`.`scrape_time`*60+60)- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 搜索的時(shí)候添加條件篩選
- 1
- 2
- 如果要用 find_in_set 需要使用到 Expression 表達(dá)式:
- 1
- 2
- 3
- 4
MySQL 數(shù)據(jù)處理
- yii2 給mysql數(shù)據(jù)庫表添加字段后,立即使用這個(gè)字段時(shí)會(huì)出現(xiàn)未定義的情況(Getting unknown property)
原因:yii 對(duì)數(shù)據(jù)表結(jié)構(gòu)進(jìn)行了緩存。
方法1. 清理掉runtime下的cache緩存之后也可以正常使用這個(gè)字段。
方法2. 修改完表字段后執(zhí)行
# 清理指定表結(jié)構(gòu)緩存數(shù)據(jù) Yii::$app->db->getSchema()->refreshTableSchema($tableName);或# 清理所有表結(jié)構(gòu)緩存數(shù)據(jù) Yii::$app->db->getSchema()->refresh();- 1
- 2
- 3
- 4
- 5
- 6
- 7
建議將以上代碼添加到修改數(shù)據(jù)表結(jié)構(gòu)的migration中。
- 字段去重的三種方法
- 1
- 2
- 3
- 4
- 5
- 6
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 1
- 2
- 3
- 事務(wù)
- 1
- 2
- 3
- 4
- 5
- 6
- 7
關(guān)于事務(wù):
Yii::$app->db->transaction(function() {$order = new Order($customer);$order->save();$order->addItems($items); });// 這相當(dāng)于下列冗長的代碼:$transaction = Yii::$app->db->beginTransaction(); try {$order = new Order($customer);$order->save();$order->addItems($items);$transaction->commit(); } catch (\Exception $e) {$transaction->rollBack();throw $e; }- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 查找 auth_times 表 type=1 并且 不存在 auth_item 表里面的數(shù)據(jù)
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
生成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- 1
- 執(zhí)行SQL查詢并緩存結(jié)果
- 1
- 2
- 3
- 4
- 批量插入數(shù)據(jù)?
第一種方法
- 1
- 2
- 3
- 4
- 5
- 6
- 7
第二種方法
$model = new User(); foreach($data as $attributes) {$model->isNewRecord = true;$model->setAttributes($attributes);$model->save() && $model->id = 0; }- 1
- 2
- 3
- 4
- 5
- 6
- 7
URL
假設(shè)我們當(dāng)前頁面的訪問地址是:http://localhost/public/index.php?r=news&id=1
- 獲取url中的host信息:
- 1
- 2
- 獲取url中的路徑信息(不包含host和參數(shù)):
- 1
- 獲取不包含host信息的url(含參數(shù)):
- 1
- 2
- 3
- 4
- 獲取完整url(含host以及參數(shù)):
- 1
- 只想獲取url中的參數(shù)部分:
- 1
- 2
- 獲取某個(gè)參數(shù)的值,比如id
- 1
- 獲取(除域名外的)首頁地址
- 1
- 2
- 獲取Referer
- 1
- 2
- 3
前端顯示
- 英文不換行問題
當(dāng)GridView和DetailView列表中的某一條內(nèi)容為連續(xù)的英文或數(shù)字(比如網(wǎng)站鏈接等)時(shí),該內(nèi)容會(huì)不換行,導(dǎo)致該列寬度被頂?shù)奶貏e長,甚至超出div的寬度。
在全局Css中添加以下樣式:
word-break:break-all; //只對(duì)英文起作用,以字母作為換行依據(jù)
eg:
html, body {height: 100%;font-family: "Microsoft YaHei";word-break: break-all; }- 1
- 2
- 3
- 4
- 5
- 6
- Yii給必填項(xiàng)加星
- 1
- 2
- 3
- 4
- 5
- 控制器獲取當(dāng)前Module name,Controller name和action name
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 寫 log 日志
- 1
- 2
- Yii2 獲取接口傳過來的 JSON 數(shù)據(jù):
- 1
- 有兩種方式獲取查詢出來的 name 為數(shù)組的集合 [name1, name2, name3]:
方式一:
return \yii\helpers\ArrayHelper::getColumn(User::find()->all(), 'name');- 1
方式二:
return User::find()->select('name')->asArray()->column();- 1
- 防止 SQL 和 Script 注入:
- 1
- 2
- 3
- 4
- 5
- 打印對(duì)象數(shù)組數(shù)據(jù):
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- restful 獲取 GET 和 POST 過來的數(shù)據(jù)(得到結(jié)果是數(shù)組):
- 1
- 2
- 3
- 4
- 5
- Yii2 生成url的兩種方式實(shí)例:
- 1
- 2
- 一個(gè)控制器調(diào)用其他控制器action的方法:
- 1
- 2
- 3
- 點(diǎn)擊下載文件 action
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 發(fā)送郵件?
a.config/config.php中的components配置
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
b.使用
Yii::$app->mailer->compose()->setFrom(['admin@gmail.com' => Yii::$app->name])->setTo('admin@gmail.com')->setSubject('test subject')->setTextBody('test body')->send();- 1
- 2
- 3
- 4
- 5
- 6
- 修改登陸狀態(tài)超時(shí)時(shí)間(到期后自動(dòng)退出登陸) config/web.php中的components
‘user’ => [?
‘class’=>’yii\web\User’,?
‘identityClass’ => ‘common\models\User’,?
‘loginUrl’=>[‘/user/sign-in/login’],?
‘a(chǎn)uthTimeout’ => 1800,//登陸有效時(shí)間?
‘a(chǎn)s afterLogin’ => ‘common\behaviors\LoginTimestampBehavior’?
],
- 修改返回的數(shù)據(jù)格式(詳見Response::FORMAT_XXXX)
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 場(chǎng)景: 數(shù)據(jù)庫有user表有個(gè)avatar_path字段用來保存用戶頭像路徑
需求: 頭像url需要通過域名http://b.com/作為基本url
目標(biāo): 提高代碼復(fù)用
此處http://b.com/可以做成一個(gè)配置- 1
示例:
User.phpclass User extends \yii\db\ActiveRecord {...public function extraFields(){$fields = parent::extraFields();$fields['avatar_url'] = function () {return empty($this->avatar_path) ? '可以設(shè)置一個(gè)默認(rèn)的頭像地址' : 'http://b.com/' . $this->avatar_path;};return $fields;}... }ExampleController.phpclass ExampleController extends \yii\web\Controller {public function actionIndex(){$userModel = User::find()->one();$userData = $userModel->toArray([], ['avatar_url']);echo $userData['avatar_url']; // 輸出內(nèi)容: http://b.com/頭像路徑} }- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- Yii2-GridView 中讓關(guān)聯(lián)字段帶搜索和排序功能?
情境要求:?
要在訂單(Order)視圖的gridview中顯示出客戶(Customer)姓名,并使其具有與其它字段相同的排序和搜索功能。
數(shù)據(jù)庫結(jié)構(gòu)?
訂單表order含有字段customer_id 與 客戶表customer的id字段關(guān)聯(lián)
首先確保在Order Model中包含以下代碼:
public function getCustomer() {return $this->hasOne(Customer::className(), ['id' => 'customer_id']); }- 1
- 2
- 3
- 4
用gii會(huì)自動(dòng)生成此代碼;
第一步:?
在OrderSearch添加一個(gè)$customer_name變量
- 1
- 2
- 3
- 4
第二步:?
修改OrderSearch中的search函數(shù)
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
- 35
- 36
- 37
- 38
- 39
第三步:?
修改order/index視圖的gridview
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 格式化輸出Json字符串
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
郵件發(fā)送
注意,使用郵件發(fā)送前發(fā)送郵件的郵箱必須開啟 POP3/SMTP/IMAP 服務(wù),請(qǐng)?jiān)卩]箱賬號(hào)設(shè)置中自行開啟
- components 配置(以126郵箱為例):
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 發(fā)送郵件
} 參考文獻(xiàn):https://blog.csdn.net/qq_16885135/article/details/52642952
總結(jié)
以上是生活随笔為你收集整理的Yii2一些方法技巧小记的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Python项目实践:蒙特卡罗方法计算圆
- 下一篇: ssh远程执行nohup命令