YII框架常用技巧总结(3)

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(含参数):

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:http://www.heiqu.com/5935.html