从多对多关系中检索数据并在json中显示对象

时间:2016-04-13 19:41:02

标签: mysql json node.js many-to-many relation

我需要使用SQL查询数据库中的数据,但说实话,我对SQL非常不满意。我有多对多关系,结果必须是JSON,就像对象而不是连续数据。这个JSON是我想要的结果,其中tagsquickTagsrelatedTo是多对多关系:

{
      "idResource": "34613b76-0116-11e6-8d21-32d288336560",
      "title": "Prof. Soledad Rath",
      "description": "Est qui iure sequi repellat rerum iste a. Animi dolorum necessitatibus et id assumenda dolores.",
      "minimumAge": "2",
      "maximumAge": "10",
      "fileName": "fuga",
      "extension": "susp",
      "URL": "https://www.Harvey.com/quia-quia-consequuntur",
      "createTime": "2016-04-12 20:22:36",
      "productionKey": "20106",
      "creatorUser": "Marlin Corkery",
      "creationCountry": "San Marino",
      "resourceType": "tempore",
      "tags": [
        {
          "name": "provident"
        }
      ],
      "quickTags": [
        {
          "name": "veritatis"
        }
      ],
      "relatedTo": [
        {
          "name": "Mr. Earl Cartwright"
        }
      ]
    },

我将从tags表和resources-tags表中提供SQL代码

-- ----------------------------
--  Table structure for `CTL_Tags`
-- ----------------------------
DROP TABLE IF EXISTS `CTL_Tags`;

CREATE TABLE `CTL_Tags` 
(
  `idTag` varchar(40) NOT NULL COMMENT 'Primary key UUID format',
  `name` varchar(45) NOT NULL COMMENT 'Name of the relationship,\nThis can be defined like:\n \nFather,\nMother,\nUncle,\nAunt,\nEtc.',
  PRIMARY KEY (`idTag`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='This table contains a Catalog of Tags of the relationships ';

-- ----------------------------
--  Table structure for `CTL_Resource_has_Tags`
-- ----------------------------
DROP TABLE IF EXISTS `CTL_Resource_has_Tags`;

CREATE TABLE `CTL_Resource_has_Tags` 
(
  `idResource` varchar(40) NOT NULL COMMENT 'Foreign key to the CTL_Resource table ',
  `idTag` varchar(40) NOT NULL COMMENT 'foreign key to the CTL_Tags table.',
  PRIMARY KEY (`idResource`,`idTag`),
  KEY `fk_CTL_Resource_has_Tag_Tag1_idx` (`idTag`),
  KEY `fk_CTL_Resource_has_Tag_CTL_Resource1_idx` (`idResource`),
  CONSTRAINT `fk_CTL_Resource_has_Tag_CTL_Resource1_idx` FOREIGN KEY (`idResource`) REFERENCES `CTL_Resource` (`idResource`) ON DELETE NO ACTION ON UPDATE NO ACTION,
  CONSTRAINT `fk_CTL_Resource_has_Tag_Tag1_idx` FOREIGN KEY (`idTag`) REFERENCES `CTL_Tags` (`idTag`) ON DELETE NO ACTION ON UPDATE NO ACTION
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='this table establishes the amount of tags that a given tag';

CTL_Resources表是

-- ----------------------------
--  Table structure for `CTL_Resource`
-- ----------------------------
DROP TABLE IF EXISTS `CTL_Resource`;

CREATE TABLE `CTL_Resource` 
(
  `idResource` varchar(40) NOT NULL DEFAULT '0' COMMENT 'Primary key UUID format',
  `idResourceType` varchar(40) NOT NULL COMMENT 'foreign key pointing to the resource type',
  `idCreatorUser` varchar(40) NOT NULL COMMENT 'Foreign key pointing to the user who created the resource\n',
  `idModifierUser` varchar(40) NOT NULL COMMENT 'Foreign key pointing to the user who modified the resource\n',
  `idCreationCountry` varchar(40) NOT NULL COMMENT 'foreign key pointing to the CTL_country table\n\nthis relationship shows the country from which the resource was created',
  `title` varchar(45) DEFAULT NULL COMMENT 'Title of the resource',
  `description` mediumtext CHARACTER SET big5 COMMENT 'Description of the resource',
  `thumbnail` varchar(1024) DEFAULT NULL COMMENT 'url/path to the thumbnail representing this resource.',
  `minimumAge` varchar(45) DEFAULT NULL COMMENT 'Minimum age required to assign  this resource',
  `maximumAge` varchar(45) DEFAULT NULL COMMENT 'Maximum age required to assign  this resource',
  `fileName` varchar(1024) DEFAULT NULL COMMENT 'url/path to the file related to this resource.',
  `extension` varchar(45) DEFAULT NULL COMMENT 'extension of the resource',
  `coachVisibility` varchar(3) DEFAULT NULL COMMENT 'Visibility status :\nVIS = visible\nINV = invisible\n',
  `studentVisibility` varchar(3) DEFAULT NULL COMMENT 'Visibility status :\nVIS = visible\nINV = invisible\n',
  `isHTML` varchar(4) DEFAULT NULL COMMENT 'If the resource is HTML this field should contain:\n\nHTML = this resource is HTML\n',
  `studentIndex` varchar(45) DEFAULT NULL COMMENT 'If the resource is HTML and/or is of type TinCan this field should contain the starting page for the student user.',
  `coachIndex` varchar(45) DEFAULT NULL COMMENT 'If the resource is HTML and/or is of type TinCan this field should contain the starting page for the coach user.',
  `isURL` varchar(45) DEFAULT NULL COMMENT 'If the resource is URL this field should contain:\n\nURL = this resource is URL\n',
  `URL` varchar(45) DEFAULT NULL COMMENT 'If the resource is URL  this field should contain the URL of the resource.',
  `source` varchar(45) DEFAULT NULL COMMENT 'It contains a description of where the resource was taken.',
  `path` varchar(250) DEFAULT NULL COMMENT 'Path in which the resource is saved physically',
  `status` varchar(3) NOT NULL DEFAULT 'ACT' COMMENT 'Code of status for internal control\nACT= Active\nINC = Inactive\nDEL = Deleted',
  `createTime` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT 'Date and time when this record was inserted into the table',
  `updateTime` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00' COMMENT 'Date and time of last update',
  `isfolder` int(11) DEFAULT NULL,
  `parentResource` varchar(40) DEFAULT NULL,
  `productionKey` varchar(15) NOT NULL COMMENT 'production keys for resources',
  PRIMARY KEY (`idResource`),
  KEY `fk_CTL_Resource_CTL_ResourceType1_idx` (`idResourceType`),
  KEY `fk_CTL_Resource_CTL_Country1_idx` (`idCreationCountry`),
  KEY `fk_CTL_Resource_CTL_KnotionUser1_idx` (`idCreatorUser`),
  KEY `fk_CTL_Resource_CTL_KnotionUser2_idx` (`idModifierUser`),
  KEY `fk_parentResource_idx` (`parentResource`),
  CONSTRAINT `fk_CTL_Resource_CTL_Country1` FOREIGN KEY (`idCreationCountry`) REFERENCES `CTL_Country` (`idCountry`) ON DELETE NO ACTION ON UPDATE NO ACTION,
  CONSTRAINT `fk_CTL_Resource_CTL_KnotionUser1` FOREIGN KEY (`idCreatorUser`) REFERENCES `OPR_User` (`idUser`) ON DELETE NO ACTION ON UPDATE NO ACTION,
  CONSTRAINT `fk_CTL_Resource_CTL_KnotionUser2` FOREIGN KEY (`idModifierUser`) REFERENCES `OPR_User` (`idUser`) ON DELETE NO ACTION ON UPDATE NO ACTION,
  CONSTRAINT `fk_CTL_Resource_CTL_ResourceType1` FOREIGN KEY (`idResourceType`) REFERENCES `CTL_ResourceType` (`idResourceType`) ON DELETE NO ACTION ON UPDATE NO ACTION,
  CONSTRAINT `fk_parentResource` FOREIGN KEY (`parentResource`) REFERENCES `CTL_Resource` (`idResource`) ON DELETE NO ACTION ON UPDATE NO ACTION
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='Catalog of resources provided by the KnotionBank';

以防万一,我正在与ExpressJS合作,没有ORM,此时我的代码就是这个

var query = `SELECT idResource, CTL_ResourceType.resourceType as resourceType, OPR_User.firstName as creatorUser, CTL_Country.country as creationCountry, title, description, CTL_Resource.thumbnail, minimumAge, maximumAge, fileName, extension, URL, source, path, productionKey
              FROM CTL_Resource
              LEFT JOIN CTL_ResourceType
                ON CTL_Resource.idResourceType = CTL_ResourceType.idResourceType
              LEFT JOIN OPR_User
                ON CTL_Resource.idCreatorUser = OPR_User.idUser
              LEFT JOIN CTL_Country
                ON CTL_Resource.idCreationCountry = CTL_Country.idCountry`


router.get('/', (req, res) => {
  connection.query(query, (err, row, fields) => {
    if (err) {
      res.json(err)
    } else {
      res.json(row)
    }
  }
)})

如果您能给予任何帮助,我将不胜感激。

1 个答案:

答案 0 :(得分:0)

如果您正在使用SQL Server,则可以使用FOR XML语法,您可以使用该语法返回与所需对象具有相同结构的XML对象。然后从XML转换为JSON。对于其他数据库,有一些相似的JSON / XML库,但我发现它们在做你正在寻找的东西时并不是非常充足。

如果您不使用SQL Server,我建议构建一个函数,该函数采用唯一命名的列并引用某种对象定义,并根据返回的结果构建对象。