Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Feathers-Sequelize: hasMany returns only first result, flattened

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?

like image 633
MrSnoozles Avatar asked Mar 07 '23 13:03

MrSnoozles


1 Answers

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);
    }
}; 
like image 87
MrSnoozles Avatar answered Apr 27 '23 17:04

MrSnoozles