[英]Storing multiple values in single SQL row
I'm trying to modelize a configuration table for my application, and I'd like to have your opinion on how to store multiple values for a configuration value. 我正在尝试为我的应用程序建模一个配置表,我想就如何为配置值存储多个值征询您的意见。
For example, how to store the available languages? 例如,如何存储可用的语言? How to store the allowed files extensions, etc.?
如何存储允许的文件扩展名等?
I'd like to have a field key
and a field value
in my table configuration
, but I have multiple ways of storing the value: 我想在表
configuration
有一个字段key
和一个字段value
,但是我有多种存储值的方法:
1,4,9,42
1,4,9,42
key
but different values
. key
但values
不同的多行。 I don't see how I could get this working, it would be very unusable... Thanks for your help :) 谢谢你的帮助 :)
Leaving aside any discussion of whether or not this is a good idea, many people do this. 撇开这是否一个好主意的讨论,许多人都这样做。 A very common approach is to have a 'blob' field on a 'configuration' table and store your data in JSON format.
一种非常常见的方法是在“配置”表上具有“ blob”字段,并以JSON格式存储数据。 You'll serialize and deserialize yourself but that's no big deal.
您将自己进行序列化和反序列化,但这没什么大不了的。
If you want to store your configuration in database (it's not recommended , but it makes sense if you have many instances of your application) - let's analyze it: 如果要将配置存储在数据库中( 不建议这样做,但是如果您有很多应用程序实例,这是有道理的)-让我们对其进行分析:
Approach with storing multiple rows with same key - let's forget about it ;) 用相同的键存储多行的方法-算了吧;)
Storing many values separated by ,
- that one would make some problems if you'll need to store value with coma (for example: 10,000
as ten thousand). 存储许多用
,
分隔的值-如果您需要用逗号存储值(例如: 10,000
等于10,000
) ,
那么这将引起一些问题。 Then you'll need to modify it to store values like in CSV file encapsulated with "
. 然后,您需要对其进行修改以存储值,例如以
"
封装的CSV文件中的值。
Best idea - storing serialized PHP values . 最好的主意- 存储序列化的PHP值 。 As your app is written in PHP that would be the best native method.
由于您的应用是用PHP编写的,因此这将是最好的本机方法。 Using this approach would be as easy as:
使用这种方法将很容易:
$configValue=unserialize(getMyValueFromDb("myKey")); $ configValue = unserialize(getMyValueFromDb(“ myKey”)); //or saving it after change $configValue="new value";
//或在更改后保存$ configValue =“ new value”; saveMyValueToDb(serialize($configValue));
saveMyValueToDb(serialize($ configValue));
Also - PHP serialize
and unserialize
take care about escaping values and convert it properly so you don't need to worry about some coma-separated-string wrongly split with explode
. 另外-PHP
serialize
和反unserialize
要注意转义值并正确转换它,因此您不必担心用逗号分隔的逗号分隔字符串会被explode
错误地分割。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.