简体   繁体   English

Sequelize - 一对多关系延迟加载并返回一个实例而不是一个集合

[英]Sequelize - One to Many relationship lazy load and return one instance and not a collection

Looking for a way to lazy load a hasMany relationship but only return one instance of the relationship instead of a collection.寻找一种延迟加载 hasMany 关系但只返回关系的一个实例而不是集合的方法。

Desired Output期望输出

{
  id: 5,
  note: 'Hello World',
  date: '2019-10-12',
}

Output I am getting我得到的输出

[
  {
    id: 5,
    note: 'Hello World',
    date: '2019-10-12',
  }
]

The code I have currently is我目前拥有的代码是

....
const note = await user.getNotes({
  limit: 1,
  where: {
    date: moment('2019-10-12')
  }
});

Is there a way when lazy loading to get just one instance of that note back as opposed to having to use note[0] after loading that relationship.有没有一种方法可以在延迟加载时只获取该笔记的一个实例,而不是在加载该关系后必须使用note[0]

The easiest way is to deconstruct the array and set the value of note to the first element:最简单的方法是解构数组并将note的值设置为第一个元素:

const [ note ] = await user.getNotes({
  limit: 1,
  where: {
    date: moment('2019-10-12')
  }
});

You can also use Note.findOne() and pass in the user.id to the where clause.您还可以使用Note.findOne()并将user.id传递给where子句。 Internally this is doing effectively the same thing as above.在内部,这有效地执行与上述相同的事情。

const note = await Note.findOne({
  limit: 1,
  where: {
    user_id: user.id,
    date: moment('2019-10-12')
  }
});

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

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