Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/node.js/39.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Mysql 在属性中获取关联的模型数据_Mysql_Node.js_Sequelize.js - Fatal编程技术网

Mysql 在属性中获取关联的模型数据

Mysql 在属性中获取关联的模型数据,mysql,node.js,sequelize.js,Mysql,Node.js,Sequelize.js,我有两种型号,User和Category 用户模型: module.exports = (sequelize, DataTypes) => { const User = sequelize.define('User', { id: { type: DataTypes.BIGINT(19), allowNull: false, primaryKey: true, autoIncrement: true }, firs

我有两种型号,
User
Category

用户模型:

module.exports = (sequelize, DataTypes) => {
  const User = sequelize.define('User', {
    id: {
      type: DataTypes.BIGINT(19),
      allowNull: false,
      primaryKey: true,
      autoIncrement: true
    },
    firstname: {
      type: DataTypes.STRING(150),
      allowNull: false
    },
    lastname: {
      type: DataTypes.STRING(150),
      allowNull: false
    },
    email: {
      type: DataTypes.STRING(255),
      allowNull: false,
      unique: true
    },
    password: {
      type: DataTypes.STRING(255),
      allowNull: false
    }
  }, {
    tableName: 'users',
    timestamps: true,
    createdAt: 'created_at',
    updatedAt: 'updated_at',
    defaultScope: {
      attributes: {
        exclude: ['password']
      }
    },
    scopes: {
      withPassword: {
        attributes: {}
      }
    }
  })

  User.prototype.toJSON = function () {
    let values = Object.assign({}, this.get())
    delete values.password
    return values
  }

  return User
}
类别模型:

module.exports = (sequelize, DataTypes) => {
  const Category = sequelize.define('Category', {
    id: {
      type: DataTypes.BIGINT(19),
      allowNull: false,
      primaryKey: true,
      autoIncrement: true
    },
    name: {
      type: DataTypes.STRING(150),
      allowNull: false
    },
    created_by: {
      type: DataTypes.BIGINT(19),
      allowNull: false,
      references: {
        model: 'users',
        key: 'id'
      }
    }
  }, {
    tableName: 'categories',
    timestamps: true,
    createdAt: 'created_at',
    updatedAt: 'updated_at'
  })

  Category.associate = (models) => {
    Category.belongsTo(models.User, {
      foreignKey: 'created_by'
    })
  }

  return Category
}
查找类别的查询:

const category = await Category.findOne({
  include: [{
    model: User,
    required: true,
    attributes: ['id', 'firstname', 'lastname', 'email']
  }],
  where: {
    id: req.params.id
  },
  limit: 1
})
当我执行查询时,我期望的响应是

{
    "id": 1,
    "name": "License",
    "created_by": {
        "id": 1,
        "firstname": "Magesh",
        "lastname": "Kumaar",
        "email": "mk@test.com"
    },
    "created_at": "2018-09-03T07:41:29.000Z",
    "updated_at": "2018-09-03T07:41:29.000Z"
}
但我得到的反应是,

{
    "id": 1,
    "name": "License",
    "created_by": 1, // I expected the user information here
    "created_at": "2018-09-03T07:41:29.000Z",
    "updated_at": "2018-09-03T07:41:29.000Z",
    "User": {
        "id": 1,
        "firstname": "Magesh",
        "lastname": "Kumaar",
        "email": "mk@test.com"
    }
}
用户信息可在由as Id创建的
和另一个包含其他信息的
user
属性中找到

我尝试了
作为
选项,但似乎不起作用。是否有任何方法可以获取由
键本身创建的
中的用户信息。

需要使用别名。

例如:

index.js

require('dotenv').load();

const { User, Category } = require('./models');
const sequelize = require('./database');

(async () => {
    await sequelize.sync({ force: true });
await Category.associate({ User });

await User.create({
    firstname: 'firstname',
    lastname: 'lastname',
    email: 'email@email.email',
    password: 'password',
});

await Category.create({
    name: 'name',
    created_by: '1',
});

const category = await Category.findOne({
    attributes: ['id'],
    include: {
        model: User,
        required: true,
        as: 'created',
        attributes: ['id', 'firstname', 'lastname', 'email']
    },
    where: {
        id: 1,
    },
});

console.log(category.toJSON());
})();
类别模型文件:

module.exports = (sequelize, DataTypes) => {
const Category = sequelize.define('Category', {
    id: {
        type: DataTypes.BIGINT(19),
        allowNull: false,
        primaryKey: true,
        autoIncrement: true
    },
    name: {
        type: DataTypes.STRING(150),
        allowNull: false
    },
    created_by: {
        type: DataTypes.BIGINT(19),
        allowNull: false,
        references: {
            model: 'users',
            key: 'id'
        }
    }
}, {
    tableName: 'categories',
    timestamps: true,
    createdAt: false,
    updatedAt: false,
});

Category.associate = (models) => {
    Category.belongsTo(models.User, {
        foreignKey: 'created_by',
        as: 'created',
    })
};

return Category;
};
结果:

{ id: 1,
  created: 
   { id: 1,
     firstname: 'firstname',
     lastname: 'lastname',
     email: 'email@email.email' } }

非常感谢您的详细回答。但是您提到了一个别名
created
,而不是在
created\u by
中写入响应。有什么方法可以做到这一点吗?唉,但没有。因此,使用了实体名称。示例:{id:1,用户:{id:1,firstname:'firstname',lastname:'lastname',电子邮件:'email@email.email你喜欢我的回答吗?如果是,给它打分。