Sequelize:无法过滤特定用户的子项表

时间:2018-02-06 12:40:23

标签: mysql node.js sequelize.js

我正在使用nodejs v8.9.0 + expressjs v4.14.0 + sequelize v3.25.0构建一个Web应用程序,人们可以在其中提出问题并发表文章。

我有这些模特:

/ **用户模型** /

module.exports = function(sequelize, DataTypes) {
var User = sequelize.define('users', {
    firstName: {
        type: DataTypes.STRING(50),
        field: 'firstName' 
    },
    lastName: {
        type: DataTypes.STRING(200),
        field: 'lastName' 
    },
    email: {
        type: DataTypes.STRING(200),
        field: 'email'
    },
},
{
    classMethods: {
        User.belongsToMany(
            models.questions, 
            {
                through: 'QuestionRecipient',  foreignKey: 'userId'
            }
        );
    }
})

/ **问题模型** /

module.exports = function(sequelize, DataTypes) {
var Question = sequelize.define('questions', {
    content: {
        type: DataTypes.TEXT,
        field: 'content' 
    },
    target: {
        type: DataTypes.INTEGER,
        field: 'target',
        defaultValue: 1 // 1 = public / 2 = private
    }
},
{
    classMethods: {
        Question.belongsToMany(
            models.users, 
            {
                through: 'QuestionRecipient',  foreignKey: 'questionId'
            }
        );
        Question.belongsTo(
            models.users, 
            {
                as: 'Creator',  foreignKey: 'creatorId'
            }
        );
    }
})

/ **文章模型** /

module.exports = function(sequelize, DataTypes) {
var Article = sequelize.define('articles', {
    content: {
        type: DataTypes.TEXT,
        field: 'content' 
    }
},
{
    classMethods: {
        Article .belongsTo(
            models.users, 
            {
                foreignKey: 'userId'
            }
        );
    }
})

/ ** FEED MODEL ** /

module.exports = function(sequelize, DataTypes) {
var Feed = sequelize.define('feeds', {}, 
{
    classMethods: {
        associate: function(models) {
            Feed.belongsTo(models.articles, {foreignKey: 'articleId'});
            Feed.belongsTo(models.questions, {foreignKey: 'questionId'});
        }
    }
}, 
{
  timestamps: true,
  freezeTableName: true
});

return Feed;
};

现在我想获取属于用户1的所有文章以及用户1创建的所有问题,并向用户1询问!我试过这个

Feed.findAll({
    attributes: ['id', 'articleId', 'questionId','createdAt', 'updatedAt'],
        include: [{
            model: Article,
            where: { userId: 1 },
            required: false,
            attributes: ['id',  'content', 'createdAt', 'userId'],
            include: [{
                model: User,
                attributes: ['id', 'firstName', 'lastName']
            }]
        },
        {
        model: Question,
        attributes: ['id', 'content', 'createdAt', 'creatorId'],
        where: { creatorId: 1 },
        required: false,
        include: [{
            model: User,
            as: 'Creator'
            attributes: ['id', 'alias', 'nom', 'prenom'],
            where: { id: 1 }
        }]
    }]

但它返回一个空数组

如何妥善管理?

0 个答案:

没有答案