我在关联2个模型时遇到问题。我将尝试尽可能详细地描述问题,希望您能对我有所帮助。
我有2个模型:Zone和PLZ(这两个都是数据库MySQL中的表)。 可以有一个具有多个PLZ的区域,一个PLZ可以属于一个区域。
在保存带有PLZ的区域时,我有一个名为“ zone_plz”的表,该表只有两列:zone_id和plz_id。两者都具有Zone.id和PLZ.id
的外键区域模型:
NSValue *val = [lineEdges objectAtIndex:0];
CGPoint p = [val CGPointValue];
PLZ模型:
const Sequelize = require('sequelize');
const sequelize = require('../util/database');
const PLZ = require('../models/PLZ');
const zone_plz = require('../models/relations/zone_plzs');
const Zone = sequelize.define('zone', {
name: {
type: Sequelize.STRING,
allowNull: false
},
color: {
type: Sequelize.STRING,
allowNull: false
}
}, {
timestamps: true
});
module.exports = Zone;
这是zone_plz模型:
const Sequelize = require('sequelize');
const sequelize = require('../util/database');
const Zone = require('../models/Zone');
const zone_plz = require('../models/relations/zone_plzs');
const PLZ = sequelize.define('plz', {
plz: {
type: Sequelize.INTEGER,
allowNull: false
},
city: {
type: Sequelize.STRING,
allowNull: false
},
district: {
type: Sequelize.STRING
}
});
module.exports = PLZ;
这就是我的查询方式:
const Sequelize = require('sequelize');
const sequelize = require('../../util/database');
const PLZ = require('../../models/PLZ');
const Zone = require('../../models/Zone');
const zone_plz = sequelize.define('zone_plz', {
zone_id: {
type: Sequelize.INTEGER,
allowNull: false,
references: {
model: Zone,
key: 'id',
}
},
plz_id: {
type: Sequelize.INTEGER,
allowNull: false,
references: {
model: PLZ,
key: 'id',
}
}
}, {
timestamps: true
});
module.exports = zone_plz;
我是新手,我也不知道这是否是正确的方法。我收到错误消息: plz与zone_plz没有关联!
有人可以帮助我吗?
答案 0 :(得分:0)
您创建了引用,而不是关联。首先,请阅读以下内容:Sequelize model references vs associations 然后在plz和区域之间创建关联,例如:
plz.belongsToMany(zone, {through: 'zone_plz'});
zone.belongsToMany(plz, {through: 'zone_plz'});