关于mysql中使用枚举类型还是int类型存取有限个固定值

来源:互联网 发布:java整形转换为字符串 编辑:程序博客网 时间:2024/05/29 07:24

其实自己并没有那么多经历去判定各自的好坏,但是为了有好的开发习惯,也是查看了很多人的回答,最后我选择的是建立类似的字典表来处理。

很多回答都提到了使用枚举类型会造成一些不必要的麻烦,甚至看到一篇文章说php是弱类型,存值是’1’,会被当成索引为1存入,这种几乎不存在的事不考虑。下面简单介绍两种存int类型,开发中的处理方式。


Model中建立数组对应

Class User{    public static $type = [        1 => '普通会员',        2 => '超级会员',        3 => '内部账号',    ];}

然后在视图中直接 User::$type[$data['type']] 进行显示,这样也方便筛选框的select建立。

也可以单独建立常量,但是建立select筛选时会麻烦一些


通过数据库存储对应关系,建立字典表

  • 一种是单表,有父id,类似无限分类
create table dictonary(    `id` int unsigned auto_increment primary key,    `name` varchar(20) not null,    `pid` int unsigned not null,    `sort` tinyint not null default 0);
  • 另一种是两表,建立一个分类表
create table dictionary_type(    `id` int unsigned auto_increment primary key,    `name` varchar(20) not null);create table dictionary_data(    `seq` int unsigned auto_increment primary key,    `id` tinyint unsigned not null,    `name` varchar(20) not null,    `sort` tinyint not null default 0,    `type` int unsigned not null);

以上两种方式,第一种就是通过文件存储了,第二种就是通过数据库管理,感觉更统筹,但是,第二种也有一个问题,就是每次都要先查总类,再去查子类列表,操作上更麻烦,有数据库开销,如果有缓存还是可以接受的。就是记得及时更新。

原创粉丝点击