I tried feathers-sequelize today for the first time and am now struggling for a couple hours already on hasMany asociations.
I want to do a simple projects
(>hasMany>) issues
relationship, but I'm just getting the first issue.
Desired output:
{
"id": 1,
"name": "Project 1",
"issues": [
{"id": 1,
"title": "Issue 1"},
{"id": 2,
"title": "Issue 2"},
]
}
Actual output:
{
"id": 1,
"name": "Project 1",
"issues.id": 1,
"issues.title": "Issue 1",
}
I generated the services with feathers-cli (v3.6.1) and added the before-hook to include the issues. My models look like this
projects.model.js:
module.exports = function (app) {
const sequelizeClient = app.get('sequelizeClient');
const projects = sequelizeClient.define('projects', {
id: { type: Sequelize.INTEGER(10).UNSIGNED, autoIncrement: true, primaryKey: true},
name: Sequelize.STRING,
},
{
hooks: {
beforeCount(options) {
options.raw = true;
}
}
});
projects.associate = function(models) {
projects.hasMany(models.issues);
};
}
issues.model.js
module.exports = function (app) {
const sequelizeClient = app.get('sequelizeClient');
const issues = sequelizeClient.define('issues', {
id: {
type: Sequelize.INTEGER(10).UNSIGNED,
autoIncrement: true,
primaryKey: true
},
project_id: {
type: Sequelize.INTEGER(10).UNSIGNED,
references: { model: 'projects' },
onDelete: 'CASCADE',
},
title: Sequelize.STRING,
}, {
hooks: {
beforeCount(options) {
options.raw = true;
}
}
});
issues.associate = function (models) {
issues.belongsTo(models.projects);
};
return issues;
};
Am I missing something obvious here?
Found the answer. The problem was not with the model definition, but with the hook for including the issue model. It needs the parameter raw: false
var includeIssues = (hook) => {
if (hook.params.query.include) {
const IssueModel = hook.app.services.issues.Model;
//
hook.params.sequelize = {
raw: false,
include: [
{model: IssueModel}
]
};
// delete any special query params so they are not used
// in the WHERE clause in the db query.
delete hook.params.query.include;
return Promise.resolve(hook);
}
};
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With