在数据库中扩展类 [英] Extending classes in the database

查看:122
本文介绍了在数据库中扩展类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在开发一个需要存储有关各种建筑物的信息的php项目,并根据建筑物的类型存储不同类型的信息:

I am working on a php project that needs to store information about various buildings and will store different types of information depending on the type of the building:

Class Building {
    var $location
    var $name
}

建筑类将由House和Office等类扩展,所以类将如下所示(仅举一个例子)

The Building class will be extended by classes like, House and Office so the classes will look like this (just an example)

Class House Extends Building {
    var $numRooms;
    var $numBathrooms;
}

Class Office extends Building {
    var $offices;
    var $sqfoot;
}

问题是,应该如何在数据库中表示(im using mysql ,如果重要)。我应该使用建筑表来存储位置和名称,然后为每个其他类创建一个表来容纳扩展变量?还是为每个类创建一个表?或者建筑表中是否有列可用于其他类的所有变量的列?

The question is, how should this be represented in a database (im using MySQL, if it matters). Should I use the building table to store the location and name and then create a table for each of the other classes to hold 'extended' variables? Or do I create a table for each class? or should the building table have columns for all the variables that can be in the other classes?

推荐答案

我强烈建议您查看Martin Fowler定义的类表继承模式。

I would strongly recommend that you look at the Class Table Inheritance pattern as defined by Martin Fowler.

此设计模式创建一个单独的表,其中保存了所有建筑物共有的数据,然后为与特定建筑类型相关的任何数据需要单独的表。有一件事我有帮助的是在父表中存储一个类型字段,以便您知道您所拥有的实体类型,而无需搜索子表来获取相应的记录。

This design pattern creates a single table that holds the data that is common to all Buildings for example and then requires a separate table for any data that is related to a specific type of building. One thing that I find helpful is to store a 'type' field in the parent table so that you know what type of entity you have without having to search the child tables for corresponding records.

我会建议,除非你有一个非常具体,明确的理由使用实体属性设计,你避免它。一方面,使用这种类型的设计来利用数据库上的约束来控制需要什么输入和允许哪些类型的值是不可能的。另一方面,它将大大减慢任何需要从这些类型的字段中提取数据的查询,因为存储在这些字段中的数据无法像您一般的索引一样。

I would recommend that unless you have a very specific, well-defined reason to use an Entity-Attribute design, that you avoid it. For one thing it becomes impossible when using this type of design to take advantage of constraints on the database to control what inputs are required and what types of values are allowed. For another, it will drastically slow down any queries that need to pull data out of those types of fields because data stored in those fields cannot be indexed like you would typically.

这篇关于在数据库中扩展类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆