Nodejs.4.41.试着通过另一张表制作两种与多对多相关的模型.带着后遗症跑-比如.
sequelize model:generate --name Camera --attributes name:string,sn:string这是模型
// Camera model
'use strict';
module.exports = (sequelize, DataTypes) => {
const Сamera = sequelize.define('Сamera', {
name: DataTypes.STRING,
sn: DataTypes.STRING
}, {});
Сamera.associate = function(models) {
// associations can be defined here
Camera.belongsToMany(models.Relay, {through: 'CameraRelay'});
};
return Сamera;
};和
// Relay model
'use strict';
module.exports = (sequelize, DataTypes) => {
const Relay = sequelize.define('Relay', {
name: DataTypes.STRING,
sn: DataTypes.STRING,
channel: DataTypes.INTEGER
}, {});
Relay.associate = function(models) {
// associations can be defined here
Relay.belongsToMany(models.Camera, {through: 'CameraRelay'});
};
return Relay;
};在文档中有几个短语
属于多个关联用于将源与多个目标连接起来。此外,目标还可以连接到多个源。
Project.belongsToMany(User, {through: 'UserProject'});User.belongsToMany(Project, {through: 'UserProject'});这将使创建一个名为UserProject的新模型,该模型具有等效的外键projectId和userId。
迁徙是
// create-relay
'use strict';
module.exports = {
up: (queryInterface, Sequelize) => {
return queryInterface.createTable('Relays', {
id: {
allowNull: false,
autoIncrement: true,
primaryKey: true,
type: Sequelize.INTEGER
},
name: {
type: Sequelize.STRING
},
sn: {
type: Sequelize.STRING
},
channel: {
type: Sequelize.INTEGER
},
createdAt: {
allowNull: false,
type: Sequelize.DATE
},
updatedAt: {
allowNull: false,
type: Sequelize.DATE
}
});
},
down: (queryInterface, Sequelize) => {
return queryInterface.dropTable('Relays');
}
};和
//create camera
'use strict';
module.exports = {
up: (queryInterface, Sequelize) => {
return queryInterface.createTable('Сameras', {
id: {
allowNull: false,
autoIncrement: true,
primaryKey: true,
type: Sequelize.INTEGER
},
name: {
type: Sequelize.STRING
},
sn: {
type: Sequelize.STRING
},
createdAt: {
allowNull: false,
type: Sequelize.DATE
},
updatedAt: {
allowNull: false,
type: Sequelize.DATE
}
});
},
down: (queryInterface, Sequelize) => {
return queryInterface.dropTable('Сameras');
}
};为什么在我运行迁移时,它不创建模型CameraRelay,而不为同一个模型创建迁移?
发布于 2019-05-29 16:53:12
我想误解是关于同步与迁移:您所指文档的很大一部分是使用同步方法创建从模型开始的所有表和关联。
当您使用迁移时,您将使用迁移文件创建db所有的表/列/关联(在我的hopinion中,这是一种更好的用于生产的方法)。
要理解不同之处,只需查看相机模型与相机迁移文件:
name和sn属性。name和sn,但也有id、createdAt和updatedAt。迁移是文件,目的是以一种安全的方式更改数据库,允许您回滚到过去的任何点。
所以,回到你的问题上,你必须:
CameraRelay迁移示例:
'use strict';
module.exports = {
up: (queryInterface, Sequelize) => {
return queryInterface.createTable('CameraRelays', {
cameraId: {
primaryKey: true,
type: Sequelize.INTEGER,
allowNull: false,
references: {
model: 'Relay',
key: 'id'
}
},
relayId: {
primaryKey: true,
type: Sequelize.INTEGER,
allowNull: false,
references: {
model: 'Camera',
key: 'id'
}
},
createdAt: {
allowNull: false,
type: Sequelize.DATE
},
updatedAt: {
allowNull: false,
type: Sequelize.DATE
}
});
},
down: (queryInterface, Sequelize) => {
return queryInterface.dropTable('CameraRelays');
}
};https://stackoverflow.com/questions/53288452
复制相似问题