YII Framework框架使用YIIC快速创建YII应用之migrate用法实例详解_php实例
本文实例讲述了YII Framework框架使用YIIC快速创建YII应用之migrate用法。分享给大家供大家参考,具体如下:
yii migrate
查看帮助
/* /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. */
在我们开发程序的过程中,数据库的结构也是不断调整的。我们的开发中要保证代码和数据库库的同步。因为我们的应用离不开数据库。例如: 在开发过程中,我们经常需要增加一个新的表,或者我们后期投入运营的产品,可能需要为某一列添加索引。我们必须保持数据结构和代码的一致性。如果代码和数据库不同步,可能整个系统将无法正常运行。出于这个原因。yii提供了一个数据库迁移工具,可以保持代码和数据库是同步。方便数据库的回滚和更新。
功能正如描述。主要提供了数据库迁移功能。
命令格式
yiic migrate [action] [parameter]
action参数用来制定执行哪一个迁移任务。可以一使用
up, down, to, create, history, new, mark.这些命令
如果没有action参数,默认为up
parameter根据action的不同而有所变化。
上述例子中给出了说明。
官方也给出了详细的例子。
http://www.yiiframework.com/doc/guide/1.1/zh_cn/database.migration#creating-migrations
这里不再详细累述。用到的时候参考使用就可以了。
补充:yii2.0使用migrate创建后台登陆
重新创建一张数据表来完成后台登陆验证
为了大家看得明白,直接贴代码
一、使用Migration创建表admin
console\migrations\m130524_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); } }
使用命令行来创建admin数据库
1、win7下使用命令:
在项目根目下,右键选择User composer here(前提是安装了全局的composer),
yii migrate
即创建数据表 admin成功
2、linux下命令一样(此处略)
二、使用gii创建模型
此处略,很简单的步聚。
注:把admin模型创在 backend/models下面 (放哪里看个人喜好)
代码如下
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; } }
三、使用migrate 为后如初使化一个登陆帐号
1、console\controllers创建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、使用命令:
在项目根目下,右键选择User composer here(前提是安装了全局的composer),
yii init/admin
到此,打开数据表看下,己经有了数据。
四、后台登陆验证
1、backend\controllers\SiteController.php 里actionLogin方法不用变
2、把common\models\LoginForm.php复制到backend\models只要把LoginForm.php里面的方法getUser()修改一个单词即可,如下
public function getUser() { if ($this->_user === false) { $this->_user = Admin::findByUsername($this->username); } return $this->_user; }
3、backend\config\main.php 只要修改
'user' => [ 'identityClass' => 'backend\models\Admin', 'enableAutoLogin' => true, ],
此外,在作修改时,请注意下命令空不要搞乱了。
到此,结束。
更多关于Yii相关内容感兴趣的读者可查看本站专题:《Yii框架入门及常用技巧总结》、《php优秀开发框架总结》、《smarty模板入门基础教程》、《php日期与时间用法总结》、《php面向对象程序设计入门教程》、《php字符串(string)用法总结》、《php+mysql数据库操作入门教程》及《php常见数据库操作技巧汇总》
希望本文所述对大家基于Yii框架的PHP程序设计有所帮助。

熱AI工具

Undresser.AI Undress
人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover
用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool
免費脫衣圖片

Clothoff.io
AI脫衣器

AI Hentai Generator
免費產生 AI 無盡。

熱門文章

熱工具

記事本++7.3.1
好用且免費的程式碼編輯器

SublimeText3漢化版
中文版,非常好用

禪工作室 13.0.1
強大的PHP整合開發環境

Dreamweaver CS6
視覺化網頁開發工具

SublimeText3 Mac版
神級程式碼編輯軟體(SublimeText3)

熱門話題

常量和變數用於在程式設計中儲存資料值。變數通常指的是可以隨時間變化的值。而常數是一種變數類型,其值在程式執行期間不能被改變。在Python中只有六個內建常數可用,它們是False、True、None、NotImplemented、Ellipsis(...)和__debug__。除了這些常數之外,Python沒有任何內建資料類型來儲存常數值。範例下面示範了常數的範例-False=100輸出SyntaxError:cannotassigntoFalseFalse是Python中的內建常數,用於儲存布林值

如何在iPhone上個人化電話Apple的iOS17引入了一項名為「聯絡人海報」的新功能,可讓您在iPhone上個性化呼叫螢幕的外觀。此功能可讓您使用所選的照片、顏色、字體和擬我表情作為聯絡人卡片設計海報。因此,當您進行通話時,您的自訂影像將完全按照您的設想顯示在收件人的iPhone上。您可以選擇與所有保存的聯絡人分享您唯一的聯絡人海報,也可以選擇可以看到它的人。同樣,在通話交流期間,您還將看到其他人的聯絡人海報。此外,Apple允許您為單一聯絡人設定特定的聯絡人照片,使來自這些聯絡人的呼叫與

本文將引起您的興趣,如果您有意在Windows上使用GIMP進行像素藝術創作。 GIMP是一款著名的圖形編輯軟體,不僅免費開源,還能幫助使用者輕鬆創造美麗的圖像和設計。除了適用於初學者和專業設計師外,GIMP也可以用於製作像素藝術,這種數位藝術形式是利用像素作為唯一構建塊來進行繪製和創作的。如何在GIMP中建立像素藝術以下是在WindowsPC上使用GIMP建立像素圖片的主要步驟:下載並安裝GIMP,然後啟動應用程式。創造一個新的形象。調整寬度和高度的大小。選擇鉛筆工具。將筆刷類型設定為像素。設定

標題:真我手機新手指南:如何在真我手機上建立資料夾?在現今社會,手機已成為人們生活中不可或缺的工具。而真我手機作為一款備受歡迎的智慧型手機品牌,其簡潔、實用的作業系統備受用戶喜愛。在使用真實我手機的過程中,很多人可能會遇到需要整理手機中的檔案和應用程式的情況,而建立資料夾就是一種有效的方式。本文將介紹如何在真我手機上建立資料夾,幫助使用者更好地管理自己的手機內容。第

很多朋友表示想知道在格力+軟體裡該怎麼去創建家庭,下面為大家帶來了操作方法,想要了解的朋友和我一起來看看吧。首先,開啟手機上的格力+軟體,並登入。接著,在頁面底部的選項列中,點選最右邊的「我的」選項,即可進入個人帳戶頁面。 2.來到我的頁面後,在“家庭”下方的選項裡有一個“創建家庭”,找到後在它的上面點擊進入。 3.接下來跳到建立家庭的頁面裡,根據提示在輸入框裡輸入要設定的家庭名稱,輸入好後在右上角點選「儲存」按鈕。 4.最後在頁面下方會彈出一個「儲存成功」的提示,代表家庭已經成功創建好了。

在本文中,我們將學習如何使用python建立使用者介面。什麼是圖形使用者介面?術語「圖形使用者介面」(或「GUI」)是指一組可以在電腦軟體中互動以顯示資訊和互動的視覺元素項目。為了回應人類輸入,物件可能會改變顏色、大小和可見度等外觀特徵。圖示、遊標和按鈕等圖形元件可以透過音訊或視覺效果(如透明度)進行增強,以建立圖形使用者介面(GUI)。如果您希望更多人使用您的平台,您需要確保它具有良好的使用者介面。這是因為這些因素的結合會極大地影響您的應用程式或網站提供的服務品質。 Python被開發人員廣泛使用,因為它提

如何使用Highcharts建立甘特圖表,需要具體程式碼範例引言:甘特圖是一種常用於展示專案進度和時間管理的圖表形式,能夠直觀地展示任務的開始時間、結束時間和進度。 Highcharts是一款功能強大的JavaScript圖表庫,提供了豐富的圖表類型和靈活的配置選項。本文將介紹如何使用Highcharts建立甘特圖表,並給出具體的程式碼範例。一、Highchart

在iOS17中,Apple為其常用的「電話」和「通訊錄」應用程式新增了聯絡人海報功能。這項功能允許用戶為每個聯絡人設置個人化的海報,使通訊錄更具視覺化和個人化。聯絡人海報可以幫助用戶更快速地識別和定位特定聯絡人,提高了用戶體驗。透過這項功能,使用者可以根據自己的喜好和需求,為每個聯絡人添加特定的圖片或標識,使通訊錄介面更加生動iOS17中的Apple為iPhone用戶提供了一種新穎的方式來表達自己,並添加了可個性化的聯繫海報。聯絡人海報功能可讓您在呼叫其他iPhone用戶時展示獨特的個人化內容。您
