淺談Node.js ORM框架Sequlize之表間關系
Sequelize模型之間存在關聯(lián)關系,這些關系代表了數(shù)據(jù)庫中對應表之間的主/外鍵關系。基于模型關系可以實現(xiàn)關聯(lián)表之間的連接查詢、更新、刪除等操作。本文將通過一個示例,介紹模型的定義,創(chuàng)建模型關聯(lián)關系,模型與關聯(lián)關系同步數(shù)據(jù)庫,及關系模型的增、刪、改、查操作。
數(shù)據(jù)庫中的表之間存在一定的關聯(lián)關系,表之間的關系基于主/外鍵進行關聯(lián)、創(chuàng)建約束等。關系表中的數(shù)據(jù)分為1對1(1:1)、1對多(1:M)、多對多(N:M)三種關聯(lián)關系。
在Sequelize中建立關聯(lián)關系,通過調(diào)用模型(源模型)的belongsTo、hasOne、hasMany、belongsToMany方法,再將要建立關系的模型(目標模型)做為參數(shù)傳入即可。這些方法會按以下規(guī)則創(chuàng)建關聯(lián)關系:
hasOne - 與目標模型建立1:1關聯(lián)關系,關聯(lián)關系(外鍵)存在于目標模型中。
belongsTo - 與目標模型建立1:1關聯(lián)關系,關聯(lián)關系(外鍵)存在于源模型中。
hasMany - 與目標模型建立1:N關聯(lián)關系,關聯(lián)關系(外鍵)存在于目標模型中。
belongsToMany - 與目標模型建立N:M關聯(lián)關系,會通過sourceId和targetId創(chuàng)建交叉表。
為了能夠清楚說明模型關系的定義及關系模型的使用,我們定義如下4個模型對象:
用戶(User)-與其它模型存在1:1、1:N、N:M
用戶登錄信息(UserCheckin)-與User存在1:1關系
用戶地址(UserAddress)-與User存在N:1關系
角色(Role)-與User存在N:M關系
這幾個模型的E-R結(jié)構如下:
接下來上代碼,代碼和瓷土不符,請注意!
代碼寫的有點low,沒辦法,!
/** * 大家就按照我的步驟來,一點一點,要有耐心哦 * 我相信,最后肯定有你想要的!加油 */ //引入框架 const Sequelize = require('sequelize'); //創(chuàng)建ORM實例 const sequelize = new Sequelize('sequlizedb', 'root', 'guoguo', { 'dialect': 'mysql', // 數(shù)據(jù)庫使用mysql } ); //驗證連接 sequelize .authenticate() .then(() => { console.log('鏈接成功'); }) .catch((error) => { console.log('鏈接失敗' + error); }) //模型的創(chuàng)建 const User = sequelize.define('user', { name: Sequelize.STRING, age: Sequelize.INTEGER, }, { freezeTableName: true, }); // User.create({ // name: 'guo', // age: 25 // }) // .then((result) => { // console.log('=======添加成功==================='); // console.log(result); // console.log('=========================='); // }) // .catch((error) => { // console.log('=========================='); // console.log('添加失敗' + error); // console.log('=========================='); // }); // const Role=sequelize.define('role',{ // name:{ // type:sequelize.STRING, // } // }, // {freezeTableName:true}); const Message = sequelize.define('message', { text: Sequelize.STRING, }, { freezeTableName: true, }); const Image = sequelize.define('image', { url: Sequelize.STRING, }, { freezeTableName: true, }); //刪除表 // sequelize.drop() // .then((logging)=>{ // console.log('=========================='); // console.log('刪除成功!'+logging); // console.log('=========================='); // }) // .catch((error)=>{ // console.log('=========================='); // console.log('刪除失敗'+error); // console.log('=========================='); // }); //建立關系 // Message.belongsTo(User); // Message.hasMany(Image); //同步到數(shù)據(jù)庫 // sequelize.sync({ // force: true, // }).then(() => { // console.log('=========================='); // console.log('同步成功'); // console.log('=========================='); // }).catch(() => { // console.log('=========================='); // console.log('同步失敗'); // console.log('=========================='); // }); //cudr function addUers(name, age) { User.create({ name: name, age: age, }).then((log) => { log = JSON.stringify(log); console.log('=========================='); console.log('增加用戶成功' + log); console.log('=========================='); }).catch((error) => { console.log('=========================='); console.log('增加用戶失敗' + error); console.log('=========================='); }); } function addMessage(userId, text) { Message.create({ text: text, userId: userId, }).then((log) => { log = JSON.stringify(log); console.log('=========================='); console.log('增加成功!' + log); console.log('=========================='); }).catch((error) => { console.log('=========================='); console.log('增加失??!' + error); console.log('=========================='); }); } function addImage(messageId, imageUrl) { Image.create({ url: imageUrl, messageId: messageId, }).then((log) => { log = JSON.stringify(log); console.log('=========================='); console.log('添加圖片成功' + log); console.log('=========================='); }).catch((error) => { console.log('=========================='); console.log('添加圖片失敗' + error); console.log('=========================='); }); } //測試 //addUers('楊雪嬌',22); //addMessage(2, '楊雪嬌發(fā)來的消息3'); // addImage(5,'http://3.png'); // addImage(6,'http://4.png'); // addImage(2,'http://2.png'); // // function getAllMessage() { Message.findAll({ where: { userId: 2 }, include: [ { model: User, attributes: [ 'id', 'name', ], }, { model: Image, attributes: [ 'id', 'url' ] } ], }).then((result) => { result = JSON.stringify(result); console.log('=========================='); console.log(result); console.log('=========================='); }).catch((error) => { console.log('=========================='); console.log('查詢失敗' + error); console.log('=========================='); }); } //測試 //getAllMessage(); //刪除消息 function delMessage(userId, messageId) { Message.destroy({ where: { userId: userId, id: messageId, }, }).then((log) => { log = JSON.stringify(log); console.log('=========================='); console.log('刪除消息成功!' + log); console.log('=========================='); }).catch((error) => { console.log('=========================='); console.log('刪除消息失?。? + error); console.log('=========================='); }); } //測試 //測試發(fā)現(xiàn)問題 如果不設置級聯(lián) 則,從屬message表的image表記錄不會刪除,而只是出現(xiàn)對應messageId 為NULL的現(xiàn)象 //delMessage(2,4); const Role = sequelize.define('role', { name: { type: Sequelize.STRING, allowNull: true, } }, { freezeTableName: true, }); //對于單個模型的同步 // Role.sync().then((log) => { // log = JSON.stringify(log); // console.log('=========================='); // console.log('Role表數(shù)據(jù)同步成功' + log); // console.log('=========================='); // Role.create({ // name: '管理員' // }).then((log) => { // log = JSON.stringify(log); // console.log('=========================='); // console.log('添加的數(shù)據(jù)為' + log); // console.log('=========================='); // }).catch((error) => { // console.log('=========================='); // console.log('添加數(shù)據(jù)失敗' + error); // console.log('=========================='); // }); // }).catch((error) => { // console.log('=========================='); // console.log('Role模型與表數(shù)據(jù)同步失敗' + error); // console.log('=========================='); // }); //定義User1模型 const User1 = sequelize.define('user1', { name: { type: Sequelize.STRING, validate: { notEmpty: true, len: [2, 30], } }, age: { type: Sequelize.STRING, defaultValue: 21, validate: { isInt: { msg: '年齡必須是整數(shù)!', } } }, email: { type: Sequelize.STRING, validate: { isEmail: true, } }, userpicture: Sequelize.STRING, }, { freezeTableName: true, }); // //同步User1模型 // User1.sync().then((log) => { // log = JSON.stringify(log); // console.log('=========================='); // console.log('User1表數(shù)據(jù)同步成功' + log); // console.log('=========================='); // }).catch((error) => { // console.log('=========================='); // console.log('User1模型與表數(shù)據(jù)同步失敗' + error); // console.log('=========================='); // }); function addUser1(userInfo) { User1.create({ name: userInfo.name, age:userInfo.age, email:userInfo.email, }).then((log) => { log = JSON.stringify(log); console.log('=========================='); console.log('添加的數(shù)據(jù)為' + log); console.log('=========================='); }).catch((error) => { console.log('=========================='); console.log('添加數(shù)據(jù)失敗' + error); console.log('=========================='); }); } const userInfo={ name:'郭東生', //age:0.1,//Validation error: 年齡必須是整數(shù)! age:22, email:'7758@qq.com', //email:'7758',//Validation error: Validation isEmail on email failed } addUser1(userInfo);
以上這篇淺談Node.js ORM框架Sequlize之表間關系就是小編分享給大家的全部內(nèi)容了,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關文章
詳解NodeJS Https HSM雙向認證實現(xiàn)
這篇文章主要介紹了詳解NodeJS Https HSM雙向認證實現(xiàn),小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2019-03-03node.js 中間件express-session使用詳解
這篇文章主要給大家介紹了node.js中間件express-session使用的相關資料,文中介紹的非常詳細,對大家具有一定的參考學習價值,需要的朋友們下面來一起看看吧。2017-05-05node.js中的http.request.end方法使用說明
這篇文章主要介紹了node.js中的http.request.end方法使用說明,本文介紹了http.request.end的方法說明、語法、接收參數(shù)、使用實例和實現(xiàn)源碼,需要的朋友可以參考下2014-12-12Node做中轉(zhuǎn)服務器轉(zhuǎn)發(fā)接口
這篇文章主要介紹了Node做中轉(zhuǎn)服務器轉(zhuǎn)發(fā)接口的相關資料,需要的朋友可以參考下2017-10-10node.js回調(diào)函數(shù)之阻塞調(diào)用與非阻塞調(diào)用
本文重點給大家介紹node.js回調(diào)函數(shù)之阻塞調(diào)用和非阻塞調(diào)用,涉及到node.js回調(diào)函數(shù)的相關知識,對本文感興趣的朋友一起學習吧2015-11-11