在 PHP 中存储复选框中的多个 Id 的可行解决方案是什么?
我有一个数据库表 prop_amenities
,其中包含以下列
这是创建表我在上表中使用的是,
CREATE TABLE `prop_amenities` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`amenity_id` int(11) NOT NULL,
`property_id` int(11) NOT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `propAmenities` (`amenity_id`,`property_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
我将为单个 property_id 存储多个便利设施 id,这是我存储的值的示例。
但是,这在插入时工作得很好,但在更新时却是一个真正的问题,例如,如果我有要删除并添加更多 amenity_id,我必须执行两次数据库操作,首先删除该值,然后添加新值。
为了让它感觉更好,我想到使用 serialize()
或 json_encode()
将 amenity_id 数组存储在数据库中。这样我可以减少列数,即每个 property_id 为一列。
使用 serialize()
后的数据库列
您认为哪种解决方案更适合这里的情况?
谢谢
i have a database table prop_amenities
which have following columns
here is the create table i am using for the above table
CREATE TABLE `prop_amenities` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`amenity_id` int(11) NOT NULL,
`property_id` int(11) NOT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `propAmenities` (`amenity_id`,`property_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
i will be storing multiple amenity id's for a single property_id, here is the example of the values i have stored.
however this works just fine while inserting, but while updating it is a real problem, if for example i have to delete and add more amenity_id i have to perform two database trip first delete the value and then add the new one.
to make it feel nicer i thought of using serialize()
or json_encode()
to store the array of amenity_id in database. this way i could reduce the number of column i.e it will be one column per property_id.
Database column after using serialize()
What do you think which solution better fits the situation here?
Thank you
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您需要问自己是否需要在查询中关心选择哪些内容。如果答案是绝对“否”,那么序列化是可以接受的。否则,请坚持使用正确标准化的形式。
You need to ask yourself if you will ever need to care in a query which ones are selected. If the answer is an absolute "no" then serialization is acceptable. Otherwise, stick to the properly-normalized form.
如果您没有超过 64 个可能的便利设施,则 SET 数据类型 可以很好地在单个列中包含特定属性的所有设施,同时比序列化值更容易查询。
If you do not have more than 64 possible amenities, the SET datatype would work nicely to contain all the amenities for a particular property in a single column, while being much easier to query than a serialized value would be.