简体   繁体   中英

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.

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.

The easiest way is to deconstruct the array and set the value of note to the first element:

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. 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')
  }
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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