简体   繁体   English

在数据库中存储JSON对象

[英]Storing a JSON object in a database

I am trying to store JSON data in a database but am having a hard time figuring out the best way to do this with MySQL. 我正在尝试将JSON数据存储在数据库中,但是很难弄清楚用MySQL做到这一点的最佳方法。

{
"id":"9",
"title":"title",
"images":[
{
"image":"house.png",
"width":"680",
"height":"780"
},{
"image":"car.png",
"width":"680",
"height":"780"
},{
"image":"dog.png",
"width":"680",
"height":"780"
}
],
"date":"1338418777"
}

So of course it is no problem to have a table with field names of id,title and date. 因此,当然,拥有一个字段名称为id,title和date的表是没有问题的。 But for 'images' it seems I would have to have a separate table with a relational setup. 但是对于“图像”,似乎我必须有一个带有关系设置的单独表。

That is ok maybe for this example where things are kind of simple but what about objects with many arrays and multiple tiers of information. 在这个例子中,事情很简单,但是具有许多数组和多层信息的对象呢?

Is there some way to approach this that doesn't lead to a very complex database? 有什么方法可以解决这个问题,但不会导致数据库非常复杂?

It is always a good practice to have images in a different tables along with a relationship.. 始终将图像与关系放到不同的 表中是一个好习惯。

Suppose you have and event photos module to make.. It is a good practice to add the event without the photos in the events table and make another table named eventPhotos that will have fields like (id, event_id, title, YOUR OTHER FIELDS) . 假设您要创建事件照片模块。最好的做法是在events表中添加不含照片的events并创建另一个名为eventPhotos表,该表将具有(id, event_id, title, YOUR OTHER FIELDS)等字段。

Finally when you need to retrieve them, simply make 2 database calls and arrange the output json as you need.. 最后,当您需要检索它们时,只需进行2个数据库调用并根据需要安排output json

This will allow you to handle the json object's key 'images' array pretty well and things will remain more simple and classified. 这将使您能够很好地处理json对象的关键“图像”数组,并且事情将变得更加简单和分类。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM