Closed
Description
Hello
I am trying out Apollostack and so far it's been great! I have a problem though :)
This question might be better asked on sequelize forums, but maybe there's some apollo feature I am not aware of ...
I have a sequelize model with parent->children relation on the same table, and I need to access parent data from inside the child's resolve functions or from inside sequelize's instance methods.
This is my sequelize model Location
module.exports = function(sequelize, DataTypes) {
return sequelize.define('Location', {
parent_id: {
type: DataTypes.INTEGER(11),
allowNull: true,
},
name: {
type: DataTypes.STRING,
allowNull: false,
},
slug: {
type: DataTypes.STRING,
allowNull: false,
}
},{
tableName: 'location',
freezeTableName: true,
instanceMethods: {
getUrl: function() {
// here I need to check if this instance is a child
// and return a different url for child
return '';
}
},
classMethods: {
associate: function(m) {
m.Location.belongsTo(m.Location, {
foreignKey: 'parent_id',
as: 'Parent'
});
m.Location.hasMany(m.Location, {
foreignKey: 'parent_id',
as: 'Locations'
});
}
}
});
};
And this are my resolve functions
const resolveFunctions = {
RootQuery: {
location(root, { slug }, context){
return Location.find({ where: { slug }, include:[{ model: Location, as: 'Locations' }] });
}
},
Location: {
parent(location){
return location.getParent();
},
locations(location){
return location.getLocations();
},
url(location){
// or here ...
// check if this location is child
// and return a different url
return location.getUrl();
}
}
}
What would be the best way to do this?
This is the solution I have come up with ... I manually inject parent data into child.
const resolveFunctions = {
RootQuery: {
// ...
},
Location: {
locations(location){
if (!location.Locations) {
return [];
}
// I can manually "inject" parent into each location
// this way I can access this.parent from within getUrl() inside instanceMethods
return location.Locations.map(l => {
l.parent = location.dataValues;
return l;
});
}
}
}
Metadata
Metadata
Assignees
Labels
No labels