0

I use express.js and sequelize, mysql

DB

A : { id: 1, name: ... }
B : { A_id: 1, name: name1 }, { A_id: 1, name: name2 }

models/A.js

A.association = models => {
 A.hasMany(models.B, { foreignKey: 'A_id' });
};
const { B } = require('../models');
A.get = _id => {
 return A.findAll({
  where: { id: _id },
  include: [{ model: B }],
 });
};

models/B.js

B.association = models => {
 B.belongsTo(models.A, { foreignKey: 'A_id' });
};

routes/test.js

A.get(1).then(record => { console.log(record); });

executed query

SELECT A.id, A.name, B.A_id, B.name
FROM A
LEFT OUTER JOIN B ON A.id = B.A_id
WHERE A.id=1;

result

should have { A_id: 1, name: name2 }

[A: {
 id: 1,
 name: ...,
 Bs: [{ A_id: 1, name: name1 }]
}];

What is the problem? query is fine. It returns data 'name1, name2'

Why Sequelize method doesn't get all of B column?

1
  • This is due to column has been same from both tables. So try to use alias if both table have same column name. Commented Aug 22, 2018 at 12:10

1 Answer 1

1

This is due to column has been same from both tables. So try to use alias if both table have same column name.

It should be something like this.

return A.findAll({
  where: { id: _id },
  include: [{ model: B }, attributes[["name", "nameb"]],
 });
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for comment :) but it doesn't work. I modified. include: [{ model: B, attributes: [['name': 'bname']] }] It just rename column. not return name2.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.