我想在sequelize中关联3个表.
我创建的模型如下.
用户模型
var Sequelize = require('sequelize');
module.exports = function(sequelize, DataTypes) {
var User = sequelize.define('User', {
uuid: {
type: Sequelize.STRING,
primaryKey: true
},
first_name: {
type: Sequelize.STRING,
allowNull: false
},
last_name: {
type: Sequelize.STRING,
allowNull: false
},
birth_date: {
type: Sequelize.DATE,
allowNull: false
},
gender: {
type: Sequelize.STRING,
allowNull: true
},
email_id: {
type: Sequelize.STRING,
allowNull: false,
validate: {
isEmail: true
}
},
contact_number: {
type: Sequelize.STRING,
allowNull: false,
validate: {
isNumeric: true
}
}
}, {
classMethods: {
associate: function(models) {
User.hasMany(models.UserSchool)
}
}
});
return User;
};
Run Code Online (Sandbox Code Playgroud)
学校模特
var Sequelize = require('sequelize');
module.exports = function(sequelize, DataTypes) {
var School = sequelize.define('School', {
school_id: {
type: Sequelize.STRING,
primaryKey: true
},
name: {
type: Sequelize.STRING,
allowNull: false
},
address: {
type: Sequelize.TEXT,
allowNull: false
},
city: {
type: Sequelize.STRING,
allowNull: false
}
}, {
classMethods: {
associate: function(models) {
School.hasMany(models.UserSchool)
}
}
});
return School;
};
Run Code Online (Sandbox Code Playgroud)
UserSchools模型
var Sequelize = require('sequelize');
module.exports = function(sequelize, DataTypes) {
var UserSchool = sequelize.define('UserSchool', {
year_of_joining: {
type: Sequelize.DATE,
allowNull: true
},
year_of_passing: {
type: Sequelize.DATE,
allowNull: true
},
school_type: {
type: Sequelize.STRING,
allowNull: false
},
course: {
type: Sequelize.STRING,
allowNull: true
}
}, {
classMethods: {
associate: function(models) {
UserSchool.belongsTo(models.User, {
onDelete: "CASCADE",
foreignKey: {
allowNull: true
}
}),
UserSchool.belongsTo(models.School, {
onDelete: "CASCADE",
foreignKey: {
allowNull: true
}
});
}
}
});
return UserSchool;
};
Run Code Online (Sandbox Code Playgroud)
当我检索用户时,userschools对象是关联的,但学校对象不是用户学校.如何创建3路关联以检索完整数据?
提前致谢.
小智 3
你也可以试试这个吗?
用户.js
classMethods: {
associate: function(models) {
// associations can be defined here
User.belongsToMany(models.School, {
through: {
model: models.UserSchool
},
foreignKey: 'uuid'
});
}
}
Run Code Online (Sandbox Code Playgroud)
学校.js
classMethods: {
associate: function(models) {
//associations can be defined here
School.belongsToMany(models.User, {
through: {
model: models.UserSchool
},
foreignKey: 'school_id'
});
}
}
Run Code Online (Sandbox Code Playgroud)
UserSchool 中没有关联。
| 归档时间: |
|
| 查看次数: |
1178 次 |
| 最近记录: |