Reputation: 912
Can't seem to find an answer to this (if there is one).
So I have 2 sequelize models. The association is working fine but I wish to alias a field from the outer model on which the inner is being performed.
When I performed this query: -
ModelOne.findAll({
attributes: ['id', ['attribute2', 'attribute2Alias'],],
include: [{
model: ModelTwo,
required: true,
attributes: [
['attribute1', 'attribute1Alias']
],
}],
})
I get back this: -
items: [{
id: 1,
attribute2Alias: 'value',
'ModelTwoTableName.attribute1Alias': 'value'
}]
I understand that I could use .map on the the returned rows but is there any way to avoid this by performing an alias directly?
Thanks.
Upvotes: 0
Views: 5856
Reputation: 1163
In stable 6.0 version of Sequelize the following works out:
ModelOne.findAll({
...
include: {association: 'modeltwos', attributes: []}
})
Note: 'modeltwos' is alias of ModelTwo, set in ModelOne model:
static associate({ ModelTwo }) {
// define association here
models.ModelOne.hasMany(ModelTwo, { as: 'modeltwos' });
}
Upvotes: 0
Reputation: 1413
I run into the same shortcoming and found the solution. You could refer to the outer column attribute from the top level attributes list. Then use sequelize.col()
together with the table name. This requires raw:true
otherwise sequelize will complain. The outer attributes list could be left empty. Like this:
ModelOne.findAll({
attributes: ['id', ['attribute2', 'attribute2Alias'], [sequelize.col('table2.attribute1'), 'attribute1Alias']],
include: [{
model: ModelTwo,
required: true,
attributes: [],
}],
raw: true,
})
Upvotes: 1
Reputation: 58593
It only happens when you use 'raw:true' in your query ,
I think the output you are showing is with raw:true
, remove that and then run your query again
Upvotes: 4