Magento2开发教程 - 如何向数据库添加新表
Magento 2具有特殊的机制,允许你创建数据库表,修改现有的,甚至添加一些数据到他们(如安装数据,已被添加在模块安装)。 这种机制允许这些变化可以在不同的设备之间传输。
关键的概念是,而不是做你能做的一次又一次重新安装系统时,手动SQL操作,开发人员创建一个安装(或升级)脚本包含数据。 每次安装模块时,脚本将被执行。
Magento 2有四种类型的脚本:installschema,installdata,upgradeschema和upgradedata。 安装脚本只执行一次,而升级脚本每次执行模块版本被更改时执行。
要查看所有四种脚本类型,我们将完成以下问候页任务:
- 创建
greeting_message表和列greeting_id 和 message. - 添加两个记录: “Happy New Year”, “Happy Holidays”.
- 接下来,修改表添加另一个字段,“season”,我们添加了记录“Happy Thanksgiving”和“Fall”。
- 更新第一和第二记录的类型。
我们需要采取的步骤来完成这些任务:
- 创建新模块.
- 创建 InstallSchema 脚本.
- 创建 InstallData 脚本.
- 添加一个新模块并验证创建数据表。
- 创建 UpgradeSchema 脚本.
- 创建 UpgradeData 脚本.
- 运行升级脚本并验证表已更改。
让我们走过每一步。
1:创建新模块
创建新模块 Learning_GreetingMessage.
进入app/code 文件夹和创建文件夹 Learning 个 Learning/GreetingMessage:
$ cd <magento2_root>/app/code
$ mkdir Learning
$ mkdir Learning/GreetingMessage
现在创建两个文件:
Learning/GreetingMessage/registration.php
/**
* Copyright © 2016 Magento. All rights reserved.
* See COPYING.txt for license details.
*/
\Magento\Framework\Component\ComponentRegistrar::register(
\Magento\Framework\Component\ComponentRegistrar::MODULE,
'Learning_GreetingMessage',
__DIR__
);
Learning/GreetingMessage/etc/module.xml
<?xml version="1.0"?>
<!--
/**
* Copyright © 2016 Magento. All rights reserved.
* * See COPYING.txt for license details.
-->
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="urn:magento:framework:Module/etc/module.xsd">
<module name="Learning_GreetingMessage" setup_version="0.0.1">
</module>
</config>
2: 创建 InstallSchema 脚本
创建一个InstallSchema脚本,在 app/code/Learning/GreetingMessage 文件夹 和创建一个Setup 文件夹。
$ cd <magento2_root>/app/code/Learning/GreetingMessage
$ mkdir Setup
创建 Setup/InstallSchema.php文件
/**
* Copyright © 2016 Magento. All rights reserved.
* See COPYING.txt for license details.
*/
namespace Learning\GreetingMessage\Setup;
use Magento\Framework\Setup\InstallSchemaInterface;
use Magento\Framework\Setup\ModuleContextInterface;
use Magento\Framework\Setup\SchemaSetupInterface;
/**
* @codeCoverageIgnore
*/
class InstallSchema implements InstallSchemaInterface
{
/**
* {@inheritdoc}
* @SuppressWarnings(PHPMD.ExcessiveMethodLength)
*/
public function install(SchemaSetupInterface $setup, ModuleContextInterface $context)
{
/**
* Create table 'greeting_message'
*/
$table = $setup->getConnection()
->newTable($setup->getTable('greeting_message'))
->addColumn(
'greeting_id',
\Magento\Framework\DB\Ddl\Table::TYPE_INTEGER,
null,
['identity' => true, 'unsigned' => true, 'nullable' => false, 'primary' => true],
'Greeting ID'
)
->addColumn(
'message',
\Magento\Framework\DB\Ddl\Table::TYPE_TEXT,
255,
['nullable' => false, 'default' => ''],
'Message'
)->setComment("Greeting Message table");
$setup->getConnection()->createTable($table);
}
}
让我们花点时间看看代码。
installschema文件都是非常典型的。 主代码位于install() 方法,有一个 $setup 参数。 这是一个关键参数,因为它提供了访问 Connection() 允许数据库操作的。
连接是 Magento\Framework\DB\Adapter\Pdo\Mysql 一个实例类。
Magento使用DDL(数据定义语言)来操纵数据库。 你可以在Magento 2核心代码找到DDL的各种例子。
3:创建 InstallData 脚本
创建 Setup/InstallData.php 文件:
/**
* Copyright © 2016 Magento. All rights reserved.
* See COPYING.txt for license details.
*/
namespace Learning\GreetingMessage\Setup;
use Magento\Framework\Setup\InstallDataInterface;
use Magento\Framework\Setup\ModuleContextInterface;
use Magento\Framework\Setup\ModuleDataSetupInterface;
/**
* @codeCoverageIgnore
*/
class InstallData implements InstallDataInterface
{
/**
* {@inheritdoc}
* @SuppressWarnings(PHPMD.CyclomaticComplexity)
* @SuppressWarnings(PHPMD.ExcessiveMethodLength)
* @SuppressWarnings(PHPMD.NPathComplexity)
*/
public function install(ModuleDataSetupInterface $setup, ModuleContextInterface $context)
{
/**
* Install messages
*/
$data = [
['message' => 'Happy New Year'],
['message' => 'Marry Christams']
];
foreach ($data as $bind) {
$setup->getConnection()
->insertForce($setup->getTable('greeting_message'), $bind);
}
}
}
4: 添加新模块并验证创建数据表
现在是运行安装脚本并验证带有初始数据的表的时候了,所以我们将运行setup:upgrade 脚本。
$ cd <magento2_root>
$ php bin/magento setup:upgrade
你应该看到一长串包含的模块Learning_GreetingMessage.
现在让我们连接数据库: mysql -u<user> -p<password> <database>
SHOW TABLES LIKE “%greeting%”
+------------------------------------+
| Tables_in_magento_210 (%greeting%) |
+------------------------------------+
| greeting_message |
+------------------------------------+
SELECT * FROM greeting_message;
+-------------+-----------------+
| greeting_id | message |
+-------------+-----------------+
| 1 | Happy New Year |
| 2 | Happy Holidays |
+-------------+-----------------+
检查表和数据是否存在
这是怎么工作的? 当你创建新模块运行 bin/magento setup:upgrade 脚本,Magento的检查代码,看有没有安装模块。 如果它找到任何,它检查是否有任何安装脚本,如果是的话,运行它们。 在那之后,Magento更新表格setup_module提出关于模块的版本信息有:
SELECT * FROM setup_module WHERE module='Learning_GreetingMessage';
+--------------------------+----------------+--------------+
| module | schema_version | data_version |
+--------------------------+----------------+--------------+
| Learning_GreetingMessage | 0.0.1 | 0.0.1 |
+--------------------------+----------------+--------------+
5: 创建 UpgradeSchema 脚本
要查看升级脚本如何工作,我们将向数据库添加一些数据。
首先,改变版本在 etc/module.xml 文件为0.0.2:
<module name="Learning_GreetingMessage" setup_version="0.0.2">
创建文件 Setup/UpgradeSchema.php:
/**
* Copyright © 2016 Magento. All rights reserved.
* See COPYING.txt for license details.
*/
namespace Learning\GreetingMessage\Setup;
use Magento\Framework\Setup\UpgradeSchemaInterface;
use Magento\Framework\Setup\ModuleContextInterface;
use Magento\Framework\Setup\SchemaSetupInterface;
/**
* Upgrade the Catalog module DB scheme
*/
class UpgradeSchema implements UpgradeSchemaInterface
{
/**
* {@inheritdoc}
*/
public function upgrade(SchemaSetupInterface $setup, ModuleContextInterface $context)
{
$setup->startSetup();
if (version_compare($context->getVersion(), '0.0.2', '<')) {
$setup->getConnection()->addColumn(
$setup->getTable('greeting_message'),
'season',
[
'type' => \Magento\Framework\DB\Ddl\Table::TYPE_TEXT,
'length' => 16,
'nullable' => false,
'default' => '',
'comment' => 'Season'
]
);
}
$setup->endSetup();
}
}
注意“version_compare”线。 如前所述,该upgradescript将每一次的版本中执行module.xml。 因此,我们只希望当前的版本升级脚本执行,而不是以前的升级。 这就是为什么我们把升级纳入“如果”条款。
6: 创建 UpgradeData 脚本
创建文件 Setup/UpgradeData.php:
/**
* Copyright © 2016 Magento. All rights reserved.
* See COPYING.txt for license details.
*/
namespace Learning\GreetingMessage\Setup;
use Magento\Framework\Setup\UpgradeDataInterface;
use Magento\Framework\Setup\ModuleContextInterface;
use Magento\Framework\Setup\ModuleDataSetupInterface;
/**
* Upgrade Data script
*/
class UpgradeData implements UpgradeDataInterface
{
/**
* {@inheritdoc}
* @SuppressWarnings(PHPMD.ExcessiveMethodLength)
*/
public function upgrade(ModuleDataSetupInterface $setup, ModuleContextInterface $context)
{
$setup->startSetup();
if ($context->getVersion()
&& version_compare($context->getVersion(), '0.0.2') < 0
) {
$table = $setup->getTable('greeting_message');
$setup->getConnection()
->insertForce($table, ['message' => 'Happy Thanksgiving, 'season' => 'fall']);
$setup->getConnection()
->update($table, ['season' => 'winter'], 'greeting_id IN (1,2)');
}
$setup->endSetup();
}
}
7: 运行升级脚本并验证表已更改
我们会再次运行setupupgrade脚本:
$ cd <magento2_root>
$ php bin/magento setup:upgrade
现在,我们可以连接到数据库,并验证我们的变化:
select * from greeting_message;
+-------------+--------------------+--------+
| greeting_id | message | season |
+-------------+--------------------+--------+
| 1 | Happy New Year | winter |
| 2 | Happy Holidays | winter |
| 3 | Happy Thanksgiving | fall |
+-------------+--------------------+--------+
Magento2开发教程 - 如何向数据库添加新表的更多相关文章
- [转]Magento2开发教程 - 如何向数据库添加新表
本文转自:https://www.cnblogs.com/xz-src/p/6920365.html Magento 2具有特殊的机制,允许你创建数据库表,修改现有的,甚至添加一些数据到他们(如安装数 ...
- iOS 9应用开发教程之使用代码添加按钮美化按钮
iOS 9应用开发教程之使用代码添加按钮美化按钮 丰富的用户界面 在iOS9中提供了很多的控件以及视图来丰富用户界面,对于这些视图以及控件我们在上一章中做了简单的介绍.本章我们将详细讲解这些视图. i ...
- 在iOS开发中,给项目添加新的.framework
首先需要了解一下iOS中静态库和动态库.framework的概念 静态库与动态库的区别 首先来看什么是库,库(Library)说白了就是一段编译好的二进制代码,加上头文件就可以供别人使用. 什么时候我 ...
- 《ArcGIS Engine+C#实例开发教程》第八讲 属性数据表的查询显示
原文:<ArcGIS Engine+C#实例开发教程>第八讲 属性数据表的查询显示 第一讲 桌面GIS应用程序框架的建立 第二讲 菜单的添加及其实现 第三讲 MapControl与Page ...
- sqlserver学习笔记(三)—— 为数据库添加新的用户
首先,用windows或sa身份登录sqlserver, 打开安全性——登录名——右键新建登录名:在选择页——常规中,新建命为user_b的登录名,选择sqlserver身份验证方式,设置密码确认密码 ...
- SQL SERVER Transactional Replication中添加新表如何不初始化整个快照
在SQL SERVER的复制(Replication)中,有可能出现由于业务需求变更,需要新增一张表或一些表到已有的复制(发布订阅)当中,这种需求应该是很正常,也很常见的.但是在已有的复制(发布订阅) ...
- 【SQL server初级】SQL SERVER Transactional Replication中添加新表如何不初始化整个快照
在SQL SERVER的复制(Replication)中,有可能出现由于业务需求变更,需要新增一张表或一些表到已有的复制(发布订阅)当中,这种需求应该是很正常,也很常见的.但是在已有的复制(发布订阅) ...
- SQL数据库添加新账号,只操作指定数据库
思路: 1.创建数据库服务器登录用户 2.创建指定数据库的用户,并且和服务器用户联系起来 3.给数据库的用户添加角色 代码实现: 1.创建名为login的服务器登录用户dba,尼玛dbpwd,默认数据 ...
- MySQL Workbench 创建数据库,添加新表,添加字段
建立数据库 第一步: 第二步: 第三步: 如图弹出弹框,继续点击Apply按钮,最后点击Finish按钮完成数据库的建立 创建表与添加字段 双击!!! 一下刚刚建立好的数据库,然后再创建表,不然会出 ...
随机推荐
- jquery chosen 插件多选初始化
<!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <m ...
- 用eFrameWork框架实现快捷搜索
软件系统最大的价值在于用心去帮客户解决各种痛点,需要做好方方面面的工作,数据的快捷搜索就是其中比较重要的一个环节.那么,什么样的搜索方式才是最高效快捷的呢?目前能想到最好的办法是用名称声母检索,用声母 ...
- 2D Convex Hulls and Extreme Points( Convex Hull Algorithms) CGAL 4.13 -User Manual
1 Introduction A subset S⊆R2 is convex if for any two points p and q in the set the line segment wit ...
- Python常用第三方模块(长期更新)
1.keyboard #监控键盘 2.PIL#处理图片 3.operator #操作列表 4.shelve #数据存储方案 保存dat文件 5.optparse #处理命令行参数 6.configpa ...
- 认识与学习shell
linux的终端机执行命令的方式,是通过bash环境来处理的.bash包括变量的设置与使用,.bash操作环境的构建.数据流重定向的功能.下面的知识,对主机的维护与管理有重要的帮助. 管理整个计算机硬 ...
- 红帽子系统链接加vm15秘钥一份
vm15秘钥:YZ718-4REEQ-08DHQ-JNYQC-ZQRD0 红帽子系统下载链接:http://www.ddooo.com/softdown/60964.htm
- Day 46 视图、存储过程、触发器、函数、事物、锁
一 .存储过程 create view stu_view as select * from ren 视图:是一个虚拟表,其内容由查询定义.同真实的表一样,视图包含一系列带有名称的列和行数据 视图有如下 ...
- java 附件上传、下载前后端代码
前言:业务需要:附件上传,需要同时满足浏览器上传,和APP上传附件,并且浏览器端不可使用form表单提交,因为表单提交无法直接获取返回值,除非刷新页面才可显示上传的附件.所以此处使用ajaxfileu ...
- C++中vector的使用
在c++中,vector是一个十分有用的容器. 作用:它能够像容器一样存放各种类型的对象,简单地说,vector是一个能够存放任意类型的动态数组,能够增加和压缩数据. vector在C++标准模板库中 ...
- hello lua
http://manual.luaer.cn/ http://www.lua.org/pil/contents.html #include <cstdio> #include <st ...