简体   繁体   English

与续集的关联

[英]Association with sequelize

I am new to node js, I have a problem trying to get records from two related tables: Province and City.我是 node js 的新手,我在尝试从两个相关表中获取记录时遇到问题:省和市。

A city has many provinces (this is my relationship)一个城市有很多省(这是我的关系)

I use this method to make the query:我使用这种方法进行查询:

async function getProvinces ()
   {
     return await municipality.findAll ({
       include: [{
           model: city,
           required: true,
           attributes: [['name', 'city']]
       }],
       attributes: ['provinceId', 'name']
     })
   }

and this returns me:这让我回来了:

[{"provinceId": 1, "name": "province 1", "city": {"city": "city 1"}}]

My problem is the following:我的问题如下:

when trying to access the city object I get an undefined当试图访问城市 object 我得到一个未定义

data [0].city.city

Why this??为什么这个??

what I need is to return a response with this format:我需要的是用这种格式返回一个响应:

{"provinceId": 1, "name": "province 1", "city": "city 1"}

Update (Example)更新(示例)

const getProvincesMethod= async ()=>
{
  const value = await getProvinces()

  if(!value) return null

  var list = []

  value.forEach(item => {
    list.push(getProvinceObject(item))
  });

  return list
}

function getProvinceObject(data)
{
  if(!data) return null
  console.log(data)
  return {
    provinceId: data.provinceId,
    name: data.name,
    city: data.city.city
  }
}

async function getProvinces ()
   {
     return await municipality.findAll ({
       include: [{
           model: city,
           required: true,
           attributes: [['name', 'city']]
       }],
       attributes: ['provinceId', 'name']
     })
   }

You can access city as follows -您可以按以下方式访问city -

data[0].dataValues.city.dataValues.city

Hope it helps!希望能帮助到你!

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

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