首页 后端开发 php教程 YII Framework框架使用YIIC快速创建YII应用之migrate用法实例详解_php实例

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

Jun 07, 2016 pm 05:08 PM
framework migrate yii 创建

本文实例讲述了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程序设计有所帮助。

本站声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn

热AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智能驱动的应用程序,用于创建逼真的裸体照片

AI Clothes Remover

AI Clothes Remover

用于从照片中去除衣服的在线人工智能工具。

Undress AI Tool

Undress AI Tool

免费脱衣服图片

Clothoff.io

Clothoff.io

AI脱衣机

AI Hentai Generator

AI Hentai Generator

免费生成ai无尽的。

热门文章

R.E.P.O.能量晶体解释及其做什么(黄色晶体)
3 周前 By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O.最佳图形设置
3 周前 By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O.如果您听不到任何人,如何修复音频
3 周前 By 尊渡假赌尊渡假赌尊渡假赌
WWE 2K25:如何解锁Myrise中的所有内容
4 周前 By 尊渡假赌尊渡假赌尊渡假赌

热工具

记事本++7.3.1

记事本++7.3.1

好用且免费的代码编辑器

SublimeText3汉化版

SublimeText3汉化版

中文版,非常好用

禅工作室 13.0.1

禅工作室 13.0.1

功能强大的PHP集成开发环境

Dreamweaver CS6

Dreamweaver CS6

视觉化网页开发工具

SublimeText3 Mac版

SublimeText3 Mac版

神级代码编辑软件(SublimeText3)

如何在Python中创建一个常量? 如何在Python中创建一个常量? Aug 29, 2023 pm 05:17 PM

常量和变量用于在编程中存储数据值。变量通常指的是可以随时间变化的值。而常量是一种变量类型,其值在程序执行期间不能被改变。在Python中只有六个内置常量可用,它们是False、True、None、NotImplemented、Ellipsis(...)和__debug__。除了这些常量之外,Python没有任何内置数据类型来存储常量值。示例下面演示了常量的示例-False=100输出SyntaxError:cannotassigntoFalseFalse是Python中的内置常量,用于存储布尔值

如何在最新的 iOS 17 上个性化你的 iPhone 电话 如何在最新的 iOS 17 上个性化你的 iPhone 电话 Sep 21, 2023 am 08:17 AM

如何在iPhone上个性化电话Apple的iOS17引入了一项名为“联系人海报”的新功能,可让您在iPhone上个性化呼叫屏幕的外观。此功能允许您使用所选的照片、颜色、字体和拟我表情作为联系人卡片设计海报。因此,当您进行通话时,您的自定义图像将完全按照您的设想显示在收件人的iPhone上。您可以选择与所有保存的联系人共享您唯一的联系人海报,也可以选择可以看到它的人。同样,在通话交流期间,您还将看到其他人的联系人海报。此外,Apple允许您为单个联系人设置特定的联系人照片,使来自这些联系人的呼叫与

如何在GIMP中创建像素艺术 如何在GIMP中创建像素艺术 Feb 19, 2024 pm 03:24 PM

本文将引起您的兴趣,如果您有意在Windows上使用GIMP进行像素艺术创作。GIMP是一款著名的图形编辑软件,不仅免费开源,还能帮助用户轻松创建出美丽的图像和设计。除了适用于初学者和专业设计师外,GIMP也可以用于制作像素艺术,这种数字艺术形式是利用像素作为唯一构建块来进行绘制和创作的。如何在GIMP中创建像素艺术以下是在WindowsPC上使用GIMP创建像素图片的主要步骤:下载并安装GIMP,然后启动应用程序。创建一个新的形象。调整宽度和高度的大小。选择铅笔工具。将笔刷类型设置为像素。设置

如何在真我手机上创建文件夹? 如何在真我手机上创建文件夹? Mar 23, 2024 pm 02:30 PM

标题:真我手机新手指南:如何在真我手机上创建文件夹?在当今社会,手机已经成为人们生活中必不可少的工具。而真我手机作为一款备受欢迎的智能手机品牌,其简洁、实用的操作系统备受用户喜爱。在使用真我手机的过程中,很多人可能会遇到需要整理手机中的文件和应用的情况,而创建文件夹就是一种有效的方式。本文将介绍如何在真我手机上创建文件夹,帮助用户更好地管理自己的手机内容。第

格力+如何创建家庭 格力+如何创建家庭 Mar 01, 2024 pm 12:40 PM

很多朋友表示想知道在格力+软件里该怎么去创建家庭,下面为大家带来了操作方法,想要了解的朋友和我一起来看看吧。首先,打开手机上的格力+软件,并登录。接着,在页面底部的选项栏中,点击最右边的“我的”选项,即可进入个人账户页面。2.来到我的页面后,在“家庭”下方的选项里有一个“创建家庭”,找到后在它的上面点击进入。3.接下来跳转到创建家庭的页面里,根据提示在输入框里输入要设置的家庭名称,输入好后在右上角点击“保存”按钮。4.最后在页面下方会弹出一个“保存成功”的提示,代表家庭已经成功创建好了。

如何通过Python创建用户界面? 如何通过Python创建用户界面? Aug 26, 2023 am 09:17 AM

在本文中,我们将学习如何使用python创建用户界面。什么是图形用户界面?术语“图形用户界面”(或“GUI”)是指一组可以在计算机软件中交互以显示信息和交互的视觉元素项目。为了响应人类输入,对象可能会改变颜色、大小和可见度等外观特征。图标、光标和按钮等图形组件可以通过音频或视觉效果(如透明度)进行增强,以创建图形用户界面(GUI)。如果您希望更多人使用您的平台,您需要确保它具有良好的用户界面。这是因为这些因素的结合会极大地影响您的应用或网站提供的服务质量。Python被开发人员广泛使用,因为它提

如何使用Highcharts创建甘特图表 如何使用Highcharts创建甘特图表 Dec 17, 2023 pm 07:23 PM

如何使用Highcharts创建甘特图表,需要具体代码示例引言:甘特图是一种常用于展示项目进度和时间管理的图表形式,能够直观地展示任务的开始时间、结束时间和进度。Highcharts是一款功能强大的JavaScript图表库,提供了丰富的图表类型和灵活的配置选项。本文将介绍如何使用Highcharts创建甘特图表,并给出具体的代码示例。一、Highchart

如何创建您的 iPhone 联系人海报 如何创建您的 iPhone 联系人海报 Mar 02, 2024 am 11:30 AM

在iOS17中,Apple为其常用的“电话”和“通讯录”应用程序新增了联系人海报功能。这一功能允许用户为每个联系人设置个性化的海报,使通讯录更具可视化和个性化。联系人海报可以帮助用户更快速地识别和定位特定联系人,提高了用户体验。通过这一功能,用户可以根据自己的喜好和需求,为每个联系人添加特定的图片或标识,使通讯录界面更加生动iOS17中的Apple为iPhone用户提供了一种新颖的方式来表达自己,并添加了可个性化的联系海报。联系人海报功能允许您在呼叫其他iPhone用户时展示独特的个性化内容。您

See all articles