Feathers-Sequelize:hasMany只返回第一个结果,扁平化

时间:2018-03-30 20:14:00

标签: sequelize.js feathersjs feathers-sequelize

我今天第一次尝试了羽毛 - 续集,现在我已经在几个小时内挣扎了很多关联。

我想做一个简单的projects(> hasMany>)issues关系,但我只是第一个问题。

期望的输出:

{
    "id": 1,
    "name": "Project 1",
    "issues": [
        {"id": 1,
        "title": "Issue 1"},
        {"id": 2,
        "title": "Issue 2"},
    ]
}

实际输出:

{
    "id": 1,
    "name": "Project 1",
    "issues.id": 1,
    "issues.title": "Issue 1",
}

我使用feathers-cli(v3.6.1)生成了服务,并添加了before-hook以包含问题。我的模型看起来像这样

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;
};

我错过了一些明显的东西吗?

1 个答案:

答案 0 :(得分:1)

找到答案。问题不在于模型定义,而是包含问题模型的钩子。它需要参数 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);
    }
};