waffl
waffl

Reputation: 5511

Sequelize: How to return relationships as JSON attribute?

I have a simple database of articles and authors.

Each article is connected to author(s) through a belongsToMany relationship, for example:

Articles

id: 1
title: Test

Authors

id: 1
name: Foo

id: 2
name: Bar

Say, for example, that the article is joined to both authors.

Using sequelize, how can I have Articles.findAll() return the authors along with its details, for example:

"articles": [
  {
    "id": 1,
    "title": "Test",
    "author_ids": "[1,2]"
  }
]

Upvotes: 1

Views: 706

Answers (1)

Evan Siroky
Evan Siroky

Reputation: 9418

Use the include option in your query:

Articles.findAll({
  include: [Author]
}).then(function(articles) {
  console.log(articles[0].authors[0].author_id);
});

Upvotes: 1

Related Questions