YII Framework框架使用YIIC快速创建YII应用之migrate用法实例详解,yiicyii
本文实例讲述了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程序设计有所帮助。
您可能感兴趣的文章:
- Laravel中Trait的用法实例详解
- Laravel中注册Facades的步骤详解
- Laravel实现构造函数自动依赖注入的方法
- Laravel使用Caching缓存数据减轻数据库查询压力的方法
- 基于laravel制作APP接口(API)
- PHP框架Laravel学习心得体会
- Laravel 中获取上一篇和下一篇数据
- Nginx中运行PHP框架Laravel的配置文件分享
- Yii使用migrate命令执行sql语句的方法
- Laravel执行migrate命令提示:No such file or directory的解决方法

每当您的Windows11或Windows10PC出现升级或更新问题时,您通常会看到一个错误代码,指示故障背后的实际原因。但是,有时,升级或更新失败可能不会显示错误代码,这时就会出现混淆。有了方便的错误代码,您就可以确切地知道问题出在哪里,因此您可以尝试修复。但是由于没有出现错误代码,因此识别问题并解决它变得极具挑战性。这会占用您大量时间来简单地找出错误背后的原因。在这种情况下,您可以尝试使用Microsoft提供的名为SetupDiag的专用工具,该工具可帮助您轻松识别错误背后的真

随着云计算技术的不断发展,数据的备份已经成为了每个企业必须要做的事情。在这样的背景下,开发一款高可用的云备份系统尤为重要。而PHP框架Yii是一款功能强大的框架,可以帮助开发者快速构建高性能的Web应用程序。下面将介绍如何使用Yii框架开发一款高可用的云备份系统。设计数据库模型在Yii框架中,数据库模型是非常重要的一部分。因为数据备份系统需要用到很多的表和关

随着互联网的不断发展,Web应用程序开发的需求也越来越高。对于开发人员而言,开发应用程序需要一个稳定、高效、强大的框架,这样可以提高开发效率。Yii是一款领先的高性能PHP框架,它提供了丰富的特性和良好的性能。Yii3是Yii框架的下一代版本,它在Yii2的基础上进一步优化了性能和代码质量。在这篇文章中,我们将介绍如何使用Yii3框架来开发PHP应用程序。

随着Web应用需求的不断增长,开发者们在选择开发框架方面也越来越有选择的余地。Symfony和Yii2是两个备受欢迎的PHP框架,它们都具有强大的功能和性能,但在面对需要开发大型Web应用时,哪个框架更适合呢?接下来我们将对Symphony和Yii2进行比较分析,以帮助你更好地进行选择。基本概述Symphony是一个由PHP编写的开源Web应用框架,它是建立

在当前信息时代,大数据、人工智能、云计算等技术已经成为了各大企业关注的热点。在这些技术中,显卡渲染技术作为一种高性能图形处理技术,受到了越来越多的关注。显卡渲染技术被广泛应用于游戏开发、影视特效、工程建模等领域。而对于开发者来说,选择一个适合自己项目的框架,是一个非常重要的决策。在当前的语言中,PHP是一种颇具活力的语言,一些优秀的PHP框架如Yii2、Ph

Yii框架是一个开源的PHPWeb应用程序框架,提供了众多的工具和组件,简化了Web应用程序开发的流程,其中数据查询是其中一个重要的组件之一。在Yii框架中,我们可以使用类似SQL的语法来访问数据库,从而高效地查询和操作数据。Yii框架的查询构建器主要包括以下几种类型:ActiveRecord查询、QueryBuilder查询、命令查询和原始SQL查询

微软刚刚修复了Windows11中的安全模式问题,但该操作系统显然在最新的累积更新中遇到了进一步的问题。KB5012643是一个包含大量修复的可选更新,它正在使使用.NET3.5框架的某些组件的应用程序崩溃。如果您长期使用Microsoft的桌面操作系统,您可能已经注意到.NETFramework。.NETFramework可能会出现在Windows更新中或某些应用程序的安装过程中。许多应用程序依赖.NETFramework才能正常运行,因为它包含开发人员在创建应用程序时

yii框架:本文为大家介绍了yii将对象转化为数组或直接输出为json格式的方法,具有一定的参考价值,希望能够帮助到大家。


핫 AI 도구

Undresser.AI Undress
사실적인 누드 사진을 만들기 위한 AI 기반 앱

AI Clothes Remover
사진에서 옷을 제거하는 온라인 AI 도구입니다.

Undress AI Tool
무료로 이미지를 벗다

Clothoff.io
AI 옷 제거제

AI Hentai Generator
AI Hentai를 무료로 생성하십시오.

인기 기사

뜨거운 도구

SublimeText3 중국어 버전
중국어 버전, 사용하기 매우 쉽습니다.

MinGW - Windows용 미니멀리스트 GNU
이 프로젝트는 osdn.net/projects/mingw로 마이그레이션되는 중입니다. 계속해서 그곳에서 우리를 팔로우할 수 있습니다. MinGW: GCC(GNU Compiler Collection)의 기본 Windows 포트로, 기본 Windows 애플리케이션을 구축하기 위한 무료 배포 가능 가져오기 라이브러리 및 헤더 파일로 C99 기능을 지원하는 MSVC 런타임에 대한 확장이 포함되어 있습니다. 모든 MinGW 소프트웨어는 64비트 Windows 플랫폼에서 실행될 수 있습니다.

Atom Editor Mac 버전 다운로드
가장 인기 있는 오픈 소스 편집기

메모장++7.3.1
사용하기 쉬운 무료 코드 편집기

mPDF
mPDF는 UTF-8로 인코딩된 HTML에서 PDF 파일을 생성할 수 있는 PHP 라이브러리입니다. 원저자인 Ian Back은 자신의 웹 사이트에서 "즉시" PDF 파일을 출력하고 다양한 언어를 처리하기 위해 mPDF를 작성했습니다. HTML2FPDF와 같은 원본 스크립트보다 유니코드 글꼴을 사용할 때 속도가 느리고 더 큰 파일을 생성하지만 CSS 스타일 등을 지원하고 많은 개선 사항이 있습니다. RTL(아랍어, 히브리어), CJK(중국어, 일본어, 한국어)를 포함한 거의 모든 언어를 지원합니다. 중첩된 블록 수준 요소(예: P, DIV)를 지원합니다.
