Backend Development
PHP Tutorial
YII Framework framework uses YIIC to quickly create YII applications. Detailed explanation of migrate usage examples, yiicyii_PHP tutorial
YII Framework framework uses YIIC to quickly create YII applications. Detailed explanation of migrate usage examples, yiicyii_PHP tutorial
YII Framework framework uses YIIC to quickly create YII applications. Detailed explanation of migrate usage examples, yiicyii
This article describes the YII Framework framework using YIIC to quickly create YII applications. Migrate usage examples. Share it with everyone for your reference, the details are as follows:
yii migrate
View help
/* /www/yii_dev/yii/framework# php yiic migrate help Error: Unknown action: help USAGE yiic migrate [action] [parameter] DESCRIPTION This command provides support for database migrations. The optional 'action' parameter specifies which specific migration task to perform. It can take these values: up, down, to, create, history, new, mark. If the 'action' parameter is not given, it defaults to 'up'. Each action takes different parameters. Their usage can be found in the following examples. EXAMPLES * yiic migrate Applies ALL new migrations. This is equivalent to 'yiic migrate to'. * yiic migrate create create_user_table Creates a new migration named 'create_user_table'. * yiic migrate up 3 Applies the next 3 new migrations. * yiic migrate down Reverts the last applied migration. * yiic migrate down 3 Reverts the last 3 applied migrations. * yiic migrate to 101129_185401 Migrates up or down to version 101129_185401. * yiic migrate mark 101129_185401 Modifies the migration history up or down to version 101129_185401. No actual migration will be performed. * yiic migrate history Shows all previously applied migration information. * yiic migrate history 10 Shows the last 10 applied migrations. * yiic migrate new Shows all new migrations. * yiic migrate new 10 Shows the next 10 migrations that have not been applied. */
As we develop the program, the structure of the database is constantly adjusted. In our development, we must ensure that the code and database library are synchronized. Because our application cannot be separated from the database. For example: During the development process, we often need to add a new table, or the products we put into operation later may need to add an index to a certain column. We must maintain consistency in data structures and code. If the code and database are out of sync, the entire system may not function properly. For this reason. Yii provides a database migration tool that can keep the code and database in sync. Facilitates database rollback and updates.
Functions as described. Mainly provides database migration function.
Command format
yiic migrate [action] [parameter]
The action parameter is used to specify which migration task to execute. Can be used instantly
up, down, to, create, history, new, mark. These commands
If there is no action parameter, the default is up
Parameter changes depending on the action.
Illustrations are given in the above example.
The official also gave detailed examples.
http://www.yiiframework.com/doc/guide/1.1/zh_cn/database.migration#creating-migrations
No more details will be given here. Just refer to it when you need it.
Supplement: yii2.0 uses migrate to create background login
Create a new data table to complete the background login verification
For everyone to understand clearly, I will post the code directly
1. Use Migration to create table admin
consolemigrationsm130524_201442_init.php
use yii\db\Schema;
use yii\db\Migration;
class m130524_201442_init extends Migration
{
const TBL_NAME = '{{%admin}}';
public function safeUp()
{
$tableOptions = null;
if ($this->db->driverName === 'mysql') {
// http://stackoverflow.com/questions/766809/whats-the-difference-between-utf8-general-ci-and-utf8-unicode-ci
$tableOptions = 'CHARACTER SET utf8 COLLATE utf8_unicode_ci ENGINE=InnoDB';
}
$this->createTable(self::TBL_NAME, [
'id' => Schema::TYPE_PK,
'username' => Schema::TYPE_STRING . ' NOT NULL',
'auth_key' => Schema::TYPE_STRING . '(32) NOT NULL',
'password_hash' => Schema::TYPE_STRING . ' NOT NULL', //密码
'password_reset_token' => Schema::TYPE_STRING,
'email' => Schema::TYPE_STRING . ' NOT NULL',
'role' => Schema::TYPE_SMALLINT . ' NOT NULL DEFAULT 10',
'status' => Schema::TYPE_SMALLINT . ' NOT NULL DEFAULT 10',
'created_at' => Schema::TYPE_INTEGER . ' NOT NULL',
'updated_at' => Schema::TYPE_INTEGER . ' NOT NULL',
], $tableOptions);
$this->createIndex('username', self::TBL_NAME, ['username'],true);
$this->createIndex('email', self::TBL_NAME, ['email'],true);
}
public function safeDown()
{
$this->dropTable(self::TBL_NAME);
}
}
Use command line to create admin database
1. Use the command under win7:
In the project root directory, right-click and select User composer here (provided that the global composer is installed),
yii migrate
The data table admin is created successfully

2. The commands under Linux are the same (omitted here)
2. Use gii to create models
Here are some simple steps.
Note: Create the admin model under backend/models (where to put it depends on personal preference)
The code is as follows
namespace backend\models;
use Yii;
use yii\base\NotSupportedException;
use yii\behaviors\TimestampBehavior;
use yii\db\ActiveRecord;
use yii\web\IdentityInterface;
/**
* This is the model class for table "{{%admin}}".
*
* @property integer $id
* @property string $username
* @property string $auth_key
* @property string $password_hash
* @property string $password_reset_token
* @property string $email
* @property integer $role
* @property integer $status
* @property integer $created_at
* @property integer $updated_at
*/
class AgAdmin extends ActiveRecord implements IdentityInterface
{
const STATUS_DELETED = 0;
const STATUS_ACTIVE = 10;
const ROLE_USER = 10;
const AUTH_KEY = '123456';
/**
* @inheritdoc
*/
public static function tableName()
{
return '{{%admin}}';
}
/**
* @inheritdoc
*/
public function behaviors()
{
return [
TimestampBehavior::className(),
];
}
/**
* @inheritdoc
*/
public function rules()
{
return [
[['username', 'email',], 'required'],
[['username', 'email'], 'string', 'max' => 255],
[['username'], 'unique'],
[['username'], 'match', 'pattern'=>'/^[a-z]\w*$/i'],
[['email'], 'unique'],
[['email'], 'email'],
['status', 'default', 'value' => self::STATUS_ACTIVE],
['status', 'in', 'range' => [self::STATUS_ACTIVE, self::STATUS_DELETED]],
['role', 'default', 'value' => self::ROLE_USER],
['auth_key', 'default', 'value' => self::AUTH_KEY],
['role', 'in', 'range' => [self::ROLE_USER]],
];
}
/**
* @inheritdoc
*/
public static function findIdentity($id)
{
return static::findOne(['id' => $id, 'status' => self::STATUS_ACTIVE]);
}
/**
* @inheritdoc
*/
public static function findIdentityByAccessToken($token, $type = null)
{
return static::findOne(['access_token' => $token]);
//throw new NotSupportedException('"findIdentityByAccessToken" is not implemented.');
}
/**
* Finds user by username
*
* @param string $username
* @return static|null
*/
public static function findByUsername($username)
{
return static::findOne(['username' => $username, 'status' => self::STATUS_ACTIVE]);
}
/**
* Finds user by password reset token
*
* @param string $token password reset token
* @return static|null
*/
public static function findByPasswordResetToken($token)
{
if (!static::isPasswordResetTokenValid($token)) {
return null;
}
return static::findOne([
'password_reset_token' => $token,
'status' => self::STATUS_ACTIVE,
]);
}
/**
* Finds out if password reset token is valid
*
* @param string $token password reset token
* @return boolean
*/
public static function isPasswordResetTokenValid($token)
{
if (empty($token)) {
return false;
}
$expire = Yii::$app->params['user.passwordResetTokenExpire'];
$parts = explode('_', $token);
$timestamp = (int) end($parts);
return $timestamp + $expire >= time();
}
/**
* @inheritdoc
*/
public function getId()
{
return $this->getPrimaryKey();
}
/**
* @inheritdoc
*/
public function getAuthKey()
{
return $this->auth_key;
}
/**
* @inheritdoc
*/
public function validateAuthKey($authKey)
{
return $this->getAuthKey() === $authKey;
}
/**
* Validates password
*
* @param string $password password to validate
* @return boolean if password provided is valid for current user
*/
public function validatePassword($password)
{
return Yii::$app->security->validatePassword($password, $this->password_hash);
}
/**
* Generates password hash from password and sets it to the model
*
* @param string $password
*/
public function setPassword($password)
{
$this->password_hash = Yii::$app->security->generatePasswordHash($password);
}
/**
* Generates "remember me" authentication key
*/
public function generateAuthKey()
{
$this->auth_key = Yii::$app->security->generateRandomString();
}
/**
* Generates new password reset token
*/
public function generatePasswordResetToken()
{
$this->password_reset_token = Yii::$app->security->generateRandomString() . '_' . time();
}
/**
* Removes password reset token
*/
public function removePasswordResetToken()
{
$this->password_reset_token = null;
}
}
3. Use migrate to create a login account for the future
1. Consolecontrollers create InitController.php
/**
*
* @author chan <maclechan@qq.com>
*/
namespace console\controllers;
use backend\models\Admin ;
class InitController extends \yii\console\Controller
{
/**
* Create init user
*/
public function actionAdmin()
{
echo "创建一个新用户 ...\n"; // 提示当前操作
$username = $this->prompt('User Name:'); // 接收用户名
$email = $this->prompt('Email:'); // 接收Email
$password = $this->prompt('Password:'); // 接收密码
$model = new AgAdmin(); // 创建一个新用户
$model->username = $username; // 完成赋值
$model->email = $email;
$model->password = $password;
if (!$model->save()) // 保存新的用户
{
foreach ($model->getErrors() as $error) // 如果保存失败,说明有错误,那就输出错误信息。
{
foreach ($error as $e)
{
echo "$e\n";
}
}
return 1; // 命令行返回1表示有异常
}
return 0; // 返回0表示一切OK
}
}
2. Use command:
In the project root directory, right-click and select User composer here (provided that the global composer is installed),
yii init/admin

At this point, open the data table and take a look. You already have the data.
4. Backend login verification
1. There is no need to change the actionLogin method in backendcontrollersSiteController.php
2. To copy commonmodelsLoginForm.php to backendmodels, just modify one word in the method getUser() in LoginForm.php, as follows
public function getUser()
{
if ($this->_user === false) {
$this->_user = Admin::findByUsername($this->username);
}
return $this->_user;
}
3. Just modify backendconfigmain.php
'user' => [ 'identityClass' => 'backend\models\Admin', 'enableAutoLogin' => true, ],
In addition, when making modifications, please be careful not to mess up the command space.
That’s it, it’s over.
Readers who are interested in more Yii-related content can check out the special topics on this site: "Introduction to Yii Framework and Summary of Common Techniques", "Summary of Excellent PHP Development Framework", "Basic Tutorial for Getting Started with Smarty Templates", "php Date and Time" Usage Summary", "php object-oriented programming introductory tutorial", "php string (string) usage summary", "php mysql database operation introductory tutorial" and "php common database operation skills summary"
I hope this article will be helpful to everyone’s PHP program design based on the Yii framework.
Articles you may be interested in:
- Detailed explanation of usage examples of Trait in Laravel
- Detailed explanation of the steps to register Facades in Laravel
- Laravel implements automatic constructor Method of Dependency Injection
- How Laravel uses Caching to cache data to reduce database query pressure
- Making APP interface (API) based on laravel
- Experience of learning PHP framework Laravel
- Get the previous and next data in Laravel
- Share the configuration file of running PHP framework Laravel in Nginx
- Yii uses the migrate command to execute sql statements
- Laravel executes the migrate command prompt: No such file or directory solution
Hot AI Tools
Undress AI Tool
Undress images for free
AI Clothes Remover
Online AI tool for removing clothes from photos.
Undresser.AI Undress
AI-powered app for creating realistic nude photos
ArtGPT
AI image generator for creative art from text prompts.
Stock Market GPT
AI powered investment research for smarter decisions
Hot Article
Popular tool
Notepad++7.3.1
Easy-to-use and free code editor
SublimeText3 Chinese version
Chinese version, very easy to use
Zend Studio 13.0.1
Powerful PHP integrated development environment
Dreamweaver CS6
Visual web development tools
SublimeText3 Mac version
God-level code editing software (SublimeText3)
Hot Topics
20446
7
13592
4
How to handle database transactions in Yii
Sep 02, 2025 am 01:46 AM
Yiiensuresdataintegritythroughtransactionmanagement,allowingrollbackonfailure.UsebeginTransaction()formanualcontrolortransaction()withaclosureforautomaticcommit/rollback.ActiveRecordmodelsautomaticallyparticipateintransactionswhenusingthesameconnecti
How to handle file uploads in Yii
Sep 01, 2025 am 01:32 AM
Answer: To handle file upload in Yii, you need to set the form enctype to multipart/form-data, use the UploadedFile class to get the file, verify the file type through the model verification rules, and save the file in the controller. Make sure that the upload directory can be written and renamed for security.
How to reset a user password in Yii
Sep 01, 2025 am 12:13 AM
Answer: To implement password reset in Yii2, you need to add password_reset_token and expiration time fields, generate a unique token and send it to the user's mailbox, and allow the user to set a new password by verifying the validity of the token, and finally clean the expired token. The specific steps include: 1. Modify the database to add token fields; 2. Implement the generatePasswordResetToken method in the User model to generate a time stamped token and set an hour validity period; 3. Create a PasswordResetRequestForm form to process the request, find the user and send an email with a reset link; 4. Define the strength of the ResetPasswordForm model to verify the new password
How to create a custom widget in Yii
Aug 30, 2025 am 12:01 AM
To create a custom widget, you need to inherit the yii\base\Widget class and implement the init() and run() methods. 2. Place the class file in the @app/widgets/ directory. 3. Use it in the view through widget() or begin() and end() syntax. 4. Complex output can render the view template through render() method. 5. Create resource packages when CSS/JS is required and register in run().
How to use Gii for code generation in Yii
Aug 31, 2025 am 06:56 AM
EnableGiiinconfig/web.phpbyaddingthemoduleandsettingallowedIPs,thenaccesshttp://your-app-url/index.php?r=gii,useModelGeneratortocreatemodelsfromdatabasetables,anduseCRUDGeneratortogeneratecontrollersandviewsforfullCRUDoperations.
How to implement search and filtering in Yii?
Sep 21, 2025 am 02:33 AM
Answer: To implement search and filtering in Yii2, you need to create a search model and use ActiveDataProvider and GridView. First, create a ProductSearch class for Product, define rules and implement search methods, process parameters through load and validate, and add conditions with andFilterWhere; instantiate the search model in the controller and pass in the request parameters; build a search form in the view with ActiveForm, GridView displays data and sets filterModel; supports advanced functions such as date range and association query to ensure database index optimization performance.
How to handle AJAX requests in Yii
Sep 04, 2025 am 02:53 AM
YiisimplifiesAJAXhandlingbyprovidingtoolstodetectAJAXrequests,returnJSONresponses,andmanageCSRFprotection.InYii2,useYii::$app->request->isAjaxtodetectAJAXcallsandsetresponse->format=Response::FORMAT_JSONforautomaticJSONencoding.Yii1usesYii::
How to implement lazy loading in Yii Active Record?
Sep 15, 2025 am 12:04 AM
LazyloadinginYiiActiveRecordautomaticallyfetchesrelateddatawhenaccessed,notduringinitialmodelload.DefinedviahasOne()orhasMany(),relationstriggeradatabasequeryonfirstaccess,asin$order->customer,whichretrievesthecustomeronlywhenneeded.Thiskeepsiniti





