侯体宗的博客
  • 首页
  • Hyperf版
  • beego仿版
  • 人生(杂谈)
  • 技术
  • 关于我
  • 更多分类
    • 文件下载
    • 文字修仙
    • 中国象棋ai
    • 群聊
    • 九宫格抽奖
    • 拼图
    • 消消乐
    • 相册

YII Framework框架使用YIIC快速创建YII应用之migrate用法实例详解

框架(架构)  /  管理员 发布于 7年前   137

本文实例讲述了YII Framework框架使用YIIC快速创建YII应用之migrate用法。分享给大家供大家参考,具体如下:

yii migrate

查看帮助

/*/www/yii_dev/yii/framework# php yiic migrate helpError: Unknown action: helpUSAGE 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 migrateApplies ALL new migrations. This is equivalent to 'yiic migrate to'.* yiic migrate create create_user_tableCreates a new migration named 'create_user_table'.* yiic migrate up 3Applies the next 3 new migrations.* yiic migrate downReverts the last applied migration.* yiic migrate down 3Reverts the last 3 applied migrations.* yiic migrate to 101129_185401Migrates up or down to version 101129_185401.* yiic migrate mark 101129_185401Modifies the migration history up or down to version 101129_185401.No actual migration will be performed.* yiic migrate historyShows all previously applied migration information.* yiic migrate history 10Shows the last 10 applied migrations.* yiic migrate newShows all new migrations.* yiic migrate new 10Shows 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  */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程序设计有所帮助。

您可能感兴趣的文章:

  • yii2框架中使用下拉菜单的自动搜索yii-widget-select2实例分析
  • Yii中创建自己的Widget实例
  • yii中widget的用法
  • PHP的Yii框架中创建视图和渲染视图的方法详解
  • YII Framework框架教程之使用YIIC快速创建YII应用详解
  • Yii中Model(模型)的创建及使用方法
  • yii实现创建验证码实例解析
  • yii框架通过控制台命令创建定时任务示例
  • yii框架源码分析之创建controller代码
  • yii2.0实现创建简单widgets示例


  • 上一条:
    Yii使用migrate命令执行sql语句的方法
    下一条:
    YII Framework框架教程之使用YIIC快速创建YII应用详解
  • 昵称:

    邮箱:

    0条评论 (评论内容有缓存机制,请悉知!)
    最新最热
    • 分类目录
    • 人生(杂谈)
    • 技术
    • linux
    • Java
    • php
    • 框架(架构)
    • 前端
    • ThinkPHP
    • 数据库
    • 微信(小程序)
    • Laravel
    • Redis
    • Docker
    • Go
    • swoole
    • Windows
    • Python
    • 苹果(mac/ios)
    • 相关文章
    • Filament v3.1版本发布(0个评论)
    • docker + gitea搭建一个git服务器流程步骤(0个评论)
    • websocket的三种架构方式使用优缺点浅析(0个评论)
    • ubuntu20.4系统中宿主机安装nginx服务,docker容器中安装php8.2实现运行laravel10框架网站(0个评论)
    • phpstudy_pro(小皮面板)中安装最新php8.2.9版本流程步骤(0个评论)
    • 近期文章
    • 在go中实现一个常用的先进先出的缓存淘汰算法示例代码(0个评论)
    • 在go+gin中使用"github.com/skip2/go-qrcode"实现url转二维码功能(0个评论)
    • 在go语言中使用api.geonames.org接口实现根据国际邮政编码获取地址信息功能(1个评论)
    • 在go语言中使用github.com/signintech/gopdf实现生成pdf分页文件功能(0个评论)
    • gmail发邮件报错:534 5.7.9 Application-specific password required...解决方案(0个评论)
    • 欧盟关于强迫劳动的规定的官方举报渠道及官方举报网站(0个评论)
    • 在go语言中使用github.com/signintech/gopdf实现生成pdf文件功能(0个评论)
    • Laravel从Accel获得5700万美元A轮融资(0个评论)
    • 在go + gin中gorm实现指定搜索/区间搜索分页列表功能接口实例(0个评论)
    • 在go语言中实现IP/CIDR的ip和netmask互转及IP段形式互转及ip是否存在IP/CIDR(0个评论)
    • 近期评论
    • 122 在

      学历:一种延缓就业设计,生活需求下的权衡之选中评论 工作几年后,报名考研了,到现在还没认真学习备考,迷茫中。作为一名北漂互联网打工人..
    • 123 在

      Clash for Windows作者删库跑路了,github已404中评论 按理说只要你在国内,所有的流量进出都在监控范围内,不管你怎么隐藏也没用,想搞你分..
    • 原梓番博客 在

      在Laravel框架中使用模型Model分表最简单的方法中评论 好久好久都没看友情链接申请了,今天刚看,已经添加。..
    • 博主 在

      佛跳墙vpn软件不会用?上不了网?佛跳墙vpn常见问题以及解决办法中评论 @1111老铁这个不行了,可以看看近期评论的其他文章..
    • 1111 在

      佛跳墙vpn软件不会用?上不了网?佛跳墙vpn常见问题以及解决办法中评论 网站不能打开,博主百忙中能否发个APP下载链接,佛跳墙或极光..
    • 2018-05
    • 2020-02
    • 2020-03
    • 2020-05
    • 2020-06
    • 2020-07
    • 2020-08
    • 2020-11
    • 2021-03
    • 2021-09
    • 2021-10
    • 2021-11
    • 2022-01
    • 2022-02
    • 2022-03
    • 2022-08
    • 2023-08
    • 2023-10
    • 2023-12
    Top

    Copyright·© 2019 侯体宗版权所有· 粤ICP备20027696号 PHP交流群

    侯体宗的博客