[英]How to deal with dynamic columns in MySQL
I have a site that has different type of products with different specifications for each of them. 我有一个站点,其中有不同类型的产品,每种产品都有不同的规格。
I want to be able to use only one products table with a set of columns but because columns are different depending on what type, I have to create multiple products table catering for each type. 我只希望使用一个带有一组列的产品表,但是由于列根据类型的不同而不同,因此我必须为每种类型创建多个产品表。 This I think is time consuming and not really effective way to manage as an ongoing solution. 我认为这是耗时且不是真正有效的作为持续解决方案进行管理的方法。
Is there a good way to manage this type of scenario with the database? 有没有一种很好的方法来通过数据库管理这种情况?
I'm using Cakephp as the framework. 我正在使用Cakephp作为框架。
规范化您的数据结构:例如,拥有一个product_info
表(FK放入products
表中),其中包含列key
和value
以表示有关每个产品的附加信息。
Martin Fowler lists three general approaches. 马丁·福勒列出了三种通用方法。
Single table is the simplest unless you have a good reason not to - just have all possible fields there, and only use the ones you need in each class. 除非您有充分的理由不这样做,否则单个表是最简单的-在那里只有所有可能的字段,并且仅在每个类中使用所需的字段。 You do have the disadvantage of not being able to enforce NOT NULL; 您确实具有不能强制执行NOT NULL的缺点; if this matters, either make a custom constraint depending on the type of object, or use option 2 or 3. 如果这很重要,请根据对象的类型进行自定义约束,或者使用选项2或3。
I wrote about using the EAV model with cake a little while ago, I think this post might be helpful, but slightly outdated. 不久前,我写过关于在蛋糕上使用EAV模型的文章,我认为这篇文章可能会有所帮助,但有点过时了。 http://nuts-and-bolts-of-cakephp.com/2010/07/27/keyvalue-tables-and-how-to-use-them-in-cakephp-1-3/ http://nuts-and-bolts-of-cakephp.com/2010/07/27/keyvalue-tables-and-how-to-to-use-them-in-cakephp-1-3/
Also, this could be very helpful for your particular question... Please take a look and study some concepts in Magento (a very popular PHP-based ecommerce framework) makes heavy use of EAV schemas and does a nice job of indexing and flattening the data. 另外,这对于您的特定问题可能非常有帮助...请看一看,研究Magento (一种非常流行的基于PHP的电子商务框架)中的一些概念,这些概念大量使用了EAV模式,并且很好地为索引和变平了数据。
You can certainly gain a lot of interesting perspective on EAV implementation. 您当然可以在EAV实现上获得很多有趣的观点。 Whether you love it or not is a different story :) 你是否爱它是一个不同的故事:)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.