Some summary of the use of YII2

Mode block assignment

The yii model provides block assignment, as follows

$values = [ 
   'name' => 'James',
   'email' => '[email protected]',
];
$customer = new Customer();
$customer->attributes = $values;
$customer->save();

Use block assignment to assign values ​​to multiple attributes at one time, but there are cases where assignments fail during use. After checking, it is found that the attributes assigned by the block must be verified by the rules in the model, or set to safe. Otherwise the assignment is 0

$model->load() data filling

$model->load(yii::$app->request->post());

You can quickly copy the data submitted by the form to the model. But it is the same as the block assignment.
Must be verified in the rules method, otherwise it cannot be assigned

Output sql statement

$query = self::findOne(1);
echo $query->createCommand()->getRawSql();

Complex SQL statement splicing

When using complex SQL in the model, Yii will have parsing errors. E.g

$query = User::find()->all();
$query->select("*,FROM_UNIXTIME('create_time','%Y-%m-%d') as date");

In the sql statement generated above, yii will treat ````FROM_UNIXTIME('create_time','%Y-%m-%d')` ``` as a field, and even report an error.

At this time, we introduce use yii\db\Expression in the head; the method of use is as follows

use yii\db\Expression;
$query = User::find()->all();
$query->select(new Expression("*,FROM_UNIXTIME('create_time','%Y-%m-%d') as date"));

Multi-condition deletion and modification

Common deletes such as: User::deleteAll(['id'=>1]);

When multiple conditions are required, the following form is required

//Multiple conditions delete

User::deleteAll(['and',['uid'=>1,'status'=>1],['>','id',100]]);
//多条件更新,跟删除类似,只是第一个数组为需要跟新的数据
User::updateAll(
    ['name'=>'wang','age'=>20],
    [
        'and',
        ['status'=>1,'sex'=>1],
        ['>','id',100]
    ]
);

The JSON method that comes with the YII framework

The data list obtained by AR cannot be serialized directly with json_encode, and data will be lost. Use yii\helpers\Json::encode($data); for serialization to ensure the integrity of the data. Pay attention to the case of the namespace. mmp, this question delayed me two hours

Use a custom model

That is to say, the table name is not specified, and it is mainly used to verify the data submitted by the user. For the new model that inherits AR by yourself, you need to pay attention to:

①不能使用$model->attributes = $param赋值,只能使用$model->load($param,'')

②不能使用场景,会提示表不存在

Get data provider data

The data object obtained by using the data provider cannot be traversed directly.

Need data = data =data= provider->getmoldes(); Obtain an array of objects, and then traverse

yii framework interface paging

Yii framework provides data and ActiveDataProvider cooperates with page widgets to realize content paging. When we use yii to write the front-end interface, we can also use the data provider to realize data paging, the steps are as follows


//每页数据量和页数
//可以在url中传入,名称可在vendor\yiisoft\yii2\data\Pagination.php 中自行定义
$page = $_GET('page');
$pagesize = $_GET('pagesize');
//设置数据查询的query
$query = User::find();
//获取数据总数
$count = $query->count();
//声明分页对象,并设置分页的相关参数
$pagination = new Pagination(['totalCount' => $count,'pagesize'=>$pagesize,'page'=>$page]);
//获取分页查询数据
$res = $query->offset($pagination->offset)
            ->limit($pagination->pagesize)
            ->all();

//在header中返回分页的相关数据
Yii::$app->getResponse()->getHeaders()
            ->set('X-Pagination-Total-Count', $pagination->totalCount)
            ->set('X-Pagination-Page-Count', $pagination->getPageCount())
            ->set('X-Pagination-Current-Page', $pagination->getPage() + 1);

data verification

You can view the official document: core validator.
Here is the prompt, when the file is verified, set
['primaryImage','file','extensions' =>['png','jpg','gif'],'maxSize' =>1024 1024 1024], 'checkExtensionByMimeType'=>false ]
checkExtensionByMimeType is true by default and needs to be set to false.
Whether to judge the file extension by the MIME type of the file. If the file extension determined by MIME is not the same as the extension of a given file, the file will be considered invalid

Guess you like

Origin blog.csdn.net/u012830303/article/details/82255813