1. AR mode removes the automatic sorting function
public function search($params) { $dataProvider = new ActiveDataProvider([ 'query' => $query, 'sort' => false, // Remove automatic sorting ]);
2. Scalar Query
The corresponding table of Book model is book, and the parameter value of $bookId is 1.
Book::find()->select('title')->where(['id' => $bookId])->scalar();
Generate SQL:
SELECT `title` FROM `book` WHERE `id` = 1
Direct output of title Value
If select('title') is not written,
Generate SQL:
SELECT * FROM `book` WHERE `id`=1
Output the value of id directly
3. Get the current Controller name and action name and modules
books under modules module
class BookController extends BaseController { public function actionIndex() { echo $this->id; echo "<pre>"; echo $this->action->id; echo "<pre>"; echo $this->module->id;//Controller Gets Current Module modules echo "<pre>"; } }
Direct output:
book
index
books
4. Do not generate label tags
// ActiveForm class $form->field($model, 'title')->textInput(['maxlength' => true])->label(false);
5. Prevent SQL and cript injection:
use yii\helpers\Html; use yii\helpers\HtmlPurifier; echo Html::encode($view); //The <script></script> code can be displayed as it is. echo HtmlPurifier::process($view); //You can filter out <script></script> code
6. greater than, less than, not equal to, equal to query
$bookArr = Book::find()->select('title') ->andWhere(['status' => 1,'del_flag' => 0])//Be equal to ->andWhere(['<>','type',1])//Not equal to ->andWhere(['>=', 'create_time', date('Y-m-d H:i:s', time())])//Greater than or equal to ->andWhere(['<=', 'create_time', date('Y-m-d H:i:s', time())])//Less than or equal to ->asArray() ->orderBy("id DESC") ->all();
7. There are two ways to get the title of the query as a collection of arrays
Method 1:
return \yii\helpers\ArrayHelper::getColumn(Book::find()->where(["category_id"=>1])->all(), 'title');
Mode two:
return Book::find()->where(["category_id"=>1])->select('title')->asArray()->column();
8. Adding Conditional Screening to Search
$dataProvider = $searchModel->search(Yii::$app->request->queryParams); // $dataProvider->query->andWhere(['cid' => 0]); $dataProvider->query->andWhere(['>', 'cid', 0]); //Optional $dataProvider->query->andFilterWhere(['id'=>isset($bookId)?$bookId:null]);
9. Remove closing spaces from form validation
public function rules() { return [[title', 'content'],'trim']]; }
10. LIKE query added unilaterally%
['LIKE', 'title', 'Wolf Road'] Will generate title LIKE '%Wolf Road%' ['LIKE', 'title', '%Wolf Road', false] => title LIKE '%Wolf Road' ['LIKE', 'title', 'Wolf Road%', false] => title LIKE 'Wolf Road%'
11. Transaction Equivalence Transform
Yii::$app->db->transaction(function () { $bookOrder = new BookOrder(); $bookOrder->save(); }); //Equivalent to $transaction = Yii::$app->db->beginTransaction(); try { $bookOrder = new BookOrder(); $bookOrder->save(); $transaction->commit(); } catch (\Exception $e) { $transaction->rollBack(); throw $e; }
12. Batch insertion of data
Method 1:
$model = new Book(); foreach ($data as $attributes) { $_model = clone $model; $_model->setAttributes($attributes); $_model->save(); }
Mode two:
$model = new Book(); foreach ($data as $attributes) { $model->isNewRecord = true; $model->setAttributes($attributes); $model->save() && $model->id = 0; }
13. Framework Model save(false) usage
In RULES rules of model class, if the contents of non-data table fields are checked, the save() method of model is usually called to make an error. At this time, it is necessary to add false parameter to save() method.
$model = new Book(); $model->title = 'Sheepskin roll'; $model->username = 'Wang Chongyang';//Assume that this field does not exist in the data table corresponding to book $model->save(false);//If there is no false parameter, the save fails
14. DetailView widget
DetailView is used to display the details of a record. The following is the case of a record:
1. Data of a Model Model Class Object
2. An instance object of ActiveRecord class
3. An associative array consisting of key-value pairs
DetailView::widget([ // Call the DetailView::widget() method 'model' => $model, // Model can be either an instance of a model class or an array. 'attributes' => [ // Attributes attributes determine which attributes of the model are displayed and how to format them 'id', [ 'attribute' => 'uid',// A more common way to show the fields of management tables 'format' => 'raw', 'value' => \backend\modules\books\models\User::getUserName($model->uid) ], 'title', 'sort', 'create_time', 'update_time', [ 'attribute' => 'del_flag', 'value' =>$model->del_flag==1?'Deleted':'Undeleted', ], ], // 'template'property adjusts the style of each row of the table 'template' => '<tr><th style="width: 120px;">{label}</th><td>{value}</td></tr>', // The'options'attribute modifies the style of the real table 'options' => ['class' => 'table table-striped table-bordered detail-view'], ])
Method getUserName in User Model
//Get user name public static function getUserName($uid){ if($uid>0){ $username = User::find()->select("username") ->where(['del_flag'=>0,'uid'=>$uid]) ->orderBy("id DESC") ->scalar(); return $username; }else{ return ""; } }
15. URL operation collation
//Get host information in url Yii::$app->request->getHostInfo(); //Get the path information in the url (excluding host and parameters): Yii::$app->request->getPathInfo(); //Get a url (with parameters) that does not contain host information: # /public/index.php?r=news&id=1; Yii::$app->request->url; //or Yii::$app->request->requestUri; //Just want to get the parameter part of the url # r=news&id=1 Yii::$app->getRequest()->queryString; //Get the value of a parameter, such as id Yii::$app->getRequest()->getQuery('id'); //get parameter 'id' //Get Home Address (Except Domain Name) # /public/index.php Yii::$app->user->returnUrl; //Get Referer Yii::$app->request->headers['Referer']; //or Yii::$app->getRequest()->getReferrer();