zoukankan      html  css  js  c++  java
  • Node.js ORM框架Sequlize之表间关系




    Sequelize模型之间存在关联关系,这些关系代表了数据库中对应表之间的主/外键关系。基于模型关系可以实现关联表之间的连接查询、更新、删除等操作。本文将通过一个示例,介绍模型的定义,创建模型关联关系,模型与关联关系同步数据库,及关系模型的增、删、改、查操作。

    数据库中的表之间存在一定的关联关系,表之间的关系基于主/外键进行关联、创建约束等。关系表中的数据分为1对1(1:1)、1对多(1:M)、多对多(N:M)三种关联关系。

    Sequelize中建立关联关系,通过调用模型(源模型)的belongsTohasOnehasManybelongsToMany方法,再将要建立关系的模型(目标模型)做为参数传入即可。这些方法会按以下规则创建关联关系:

    • hasOne - 与目标模型建立1:1关联关系,关联关系(外键)存在于目标模型中。
    • belongsTo - 与目标模型建立1:1关联关系,关联关系(外键)存在于源模型中。
    • hasMany - 与目标模型建立1:N关联关系,关联关系(外键)存在于目标模型中。
    • belongsToMany - 与目标模型建立N:M关联关系,会通过sourceIdtargetId创建交叉表。

    为了能够清楚说明模型关系的定义及关系模型的使用,我们定义如下4个模型对象:

    • 用户(User)-与其它模型存在1:11:NN:M
    • 用户登录信息(UserCheckin)-与User存在1:1关系
    • 用户地址(UserAddress)-与User存在N:1关系
    • 角色(Role)-与User存在N:M关系

    这几个模型的E-R结构如下:

    接下来上代码,代码和瓷土不符,请注意!


    代码写的有点low,没办法,!

      1 /**
      2  * 大家就按照我的步骤来,一点一点,要有耐心哦
      3  * 我相信,最后肯定有你想要的!加油
      4  */
      5 //引入框架
      6 const Sequelize = require('sequelize');
      7 //创建ORM实例
      8 const sequelize = new Sequelize('sequlizedb', 'root', 'guoguo',
      9     {
     10         'dialect': 'mysql',  // 数据库使用mysql
     11     }
     12 );
     13 //验证连接
     14 sequelize
     15     .authenticate()
     16     .then(() => {
     17         console.log('链接成功');
     18     })
     19     .catch((error) => {
     20         console.log('链接失败' + error);
     21     })
     22 //模型的创建
     23 
     24 const User = sequelize.define('user', {
     25     name: Sequelize.STRING,
     26     age: Sequelize.INTEGER,
     27 }, {
     28         freezeTableName: true,
     29     });
     30 
     31 // User.create({
     32 //     name: 'guo',
     33 //     age: 25
     34 // })
     35 //     .then((result) => {
     36 //         console.log('=======添加成功===================');
     37 //         console.log(result);
     38 //         console.log('==========================');
     39 
     40 //     })
     41 //     .catch((error) => {
     42 //         console.log('==========================');
     43 //         console.log('添加失败' + error);
     44 //         console.log('==========================');
     45 
     46 //     });
     47 
     48 // const Role=sequelize.define('role',{
     49 //     name:{
     50 //         type:sequelize.STRING,
     51 //     }
     52 // },
     53 // {freezeTableName:true});
     54 
     55 
     56 const Message = sequelize.define('message', {
     57     text: Sequelize.STRING,
     58 }, {
     59         freezeTableName: true,
     60     });
     61 
     62 const Image = sequelize.define('image', {
     63     url: Sequelize.STRING,
     64 }, {
     65         freezeTableName: true,
     66     });
     67 //删除表
     68 // sequelize.drop()
     69 // .then((logging)=>{
     70 //     console.log('==========================');
     71 //     console.log('删除成功!'+logging);
     72 //     console.log('==========================');
     73 
     74 // })
     75 // .catch((error)=>{
     76 //     console.log('==========================');
     77 //     console.log('删除失败'+error);
     78 //     console.log('==========================');
     79 
     80 // });
     81 
     82 //建立关系
     83 // Message.belongsTo(User);
     84 // Message.hasMany(Image);
     85 //同步到数据库
     86 // sequelize.sync({
     87 //     force: true,
     88 // }).then(() => {
     89 //     console.log('==========================');
     90 //     console.log('同步成功');
     91 //     console.log('==========================');
     92 
     93 // }).catch(() => {
     94 //     console.log('==========================');
     95 //     console.log('同步失败');
     96 //     console.log('==========================');
     97 
     98 // });
     99 
    100 //cudr
    101 function addUers(name, age) {
    102     User.create({
    103         name: name,
    104         age: age,
    105     }).then((log) => {
    106         log = JSON.stringify(log);
    107         console.log('==========================');
    108         console.log('增加用户成功' + log);
    109         console.log('==========================');
    110 
    111     }).catch((error) => {
    112         console.log('==========================');
    113         console.log('增加用户失败' + error);
    114         console.log('==========================');
    115 
    116     });
    117 
    118 }
    119 function addMessage(userId, text) {
    120     Message.create({
    121         text: text,
    122         userId: userId,
    123     }).then((log) => {
    124         log = JSON.stringify(log);
    125         console.log('==========================');
    126         console.log('增加成功!' + log);
    127         console.log('==========================');
    128 
    129     }).catch((error) => {
    130         console.log('==========================');
    131         console.log('增加失败!' + error);
    132         console.log('==========================');
    133 
    134     });
    135 }
    136 function addImage(messageId, imageUrl) {
    137     Image.create({
    138         url: imageUrl,
    139         messageId: messageId,
    140     }).then((log) => {
    141         log = JSON.stringify(log);
    142         console.log('==========================');
    143         console.log('添加图片成功' + log);
    144         console.log('==========================');
    145 
    146     }).catch((error) => {
    147         console.log('==========================');
    148         console.log('添加图片失败' + error);
    149         console.log('==========================');
    150 
    151     });
    152 }
    153 //测试
    154 //addUers('杨雪娇',22);
    155 //addMessage(2, '杨雪娇发来的消息3');
    156 
    157 // addImage(5,'http://3.png');
    158 // addImage(6,'http://4.png');
    159 // addImage(2,'http://2.png');
    160 // //
    161 function getAllMessage() {
    162     Message.findAll({
    163         where: {
    164             userId: 2
    165         },
    166         include: [
    167             {
    168                 model: User,
    169                 attributes: [
    170                     'id',
    171                     'name',
    172                 ],
    173             },
    174             {
    175                 model: Image,
    176                 attributes: [
    177                     'id',
    178                     'url'
    179                 ]
    180             }
    181         ],
    182     }).then((result) => {
    183         result = JSON.stringify(result);
    184         console.log('==========================');
    185         console.log(result);
    186         console.log('==========================');
    187 
    188 
    189     }).catch((error) => {
    190         console.log('==========================');
    191         console.log('查询失败' + error);
    192         console.log('==========================');
    193 
    194     });
    195 }
    196 //测试
    197 //getAllMessage();
    198 //删除消息
    199 function delMessage(userId, messageId) {
    200     Message.destroy({
    201         where: {
    202             userId: userId,
    203             id: messageId,
    204         },
    205 
    206     }).then((log) => {
    207         log = JSON.stringify(log);
    208         console.log('==========================');
    209         console.log('删除消息成功!' + log);
    210         console.log('==========================');
    211 
    212     }).catch((error) => {
    213         console.log('==========================');
    214         console.log('删除消息失败!' + error);
    215         console.log('==========================');
    216 
    217     });
    218 }
    219 //测试
    220 //测试发现问题 如果不设置级联 则,从属message表的image表记录不会删除,而只是出现对应messageId 为NULL的现象
    221 //delMessage(2,4);
    222 
    223 const Role = sequelize.define('role', {
    224     name: {
    225         type: Sequelize.STRING, allowNull: true,
    226     }
    227 }, {
    228         freezeTableName: true,
    229     });
    230 
    231 
    232 //对于单个模型的同步
    233 // Role.sync().then((log) => {
    234 //     log = JSON.stringify(log);
    235 //     console.log('==========================');
    236 //     console.log('Role表数据同步成功' + log);
    237 //     console.log('==========================');
    238 //     Role.create({
    239 //         name: '管理员'
    240 //     }).then((log) => {
    241 //         log = JSON.stringify(log);
    242 //         console.log('==========================');
    243 //         console.log('添加的数据为' + log);
    244 //         console.log('==========================');
    245 
    246 //     }).catch((error) => {
    247 //         console.log('==========================');
    248 //         console.log('添加数据失败' + error);
    249 //         console.log('==========================');
    250 
    251 //     });
    252 
    253 // }).catch((error) => {
    254 //     console.log('==========================');
    255 //     console.log('Role模型与表数据同步失败' + error);
    256 //     console.log('==========================');
    257 
    258 // });
    259 
    260 //定义User1模型
    261 const User1 = sequelize.define('user1', {
    262     name: {
    263         type: Sequelize.STRING,
    264         validate: {
    265             notEmpty: true,
    266             len: [2, 30],
    267         }
    268     },
    269     age: {
    270         type: Sequelize.STRING,
    271         defaultValue: 21,
    272         validate: {
    273             isInt: {
    274                 msg: '年龄必须是整数!',
    275             }
    276         }
    277 
    278     },
    279     email: {
    280         type: Sequelize.STRING,
    281         validate: {
    282             isEmail: true,
    283         }
    284     },
    285     userpicture: Sequelize.STRING,
    286 }, {
    287         freezeTableName: true,
    288     });
    289 //
    290 //同步User1模型
    291 // User1.sync().then((log) => {
    292 //     log = JSON.stringify(log);
    293 //     console.log('==========================');
    294 //     console.log('User1表数据同步成功' + log);
    295 //     console.log('==========================');
    296 // }).catch((error) => {
    297 //     console.log('==========================');
    298 //     console.log('User1模型与表数据同步失败' + error);
    299 //     console.log('==========================');
    300 // });
    301 
    302 function addUser1(userInfo) {
    303     User1.create({
    304         name: userInfo.name,
    305         age:userInfo.age,
    306         email:userInfo.email,
    307     }).then((log) => {
    308         log = JSON.stringify(log);
    309         console.log('==========================');
    310         console.log('添加的数据为' + log);
    311         console.log('==========================');
    312 
    313     }).catch((error) => {
    314         console.log('==========================');
    315         console.log('添加数据失败' + error);
    316         console.log('==========================');
    317 
    318     });
    319 }
    320 const userInfo={
    321     name:'郭东生',
    322     //age:0.1,//Validation error: 年龄必须是整数!
    323     age:22,
    324     email:'7758@qq.com',
    325     //email:'7758',//Validation error: Validation isEmail on email failed
    326 }
    327 addUser1(userInfo);
  • 相关阅读:
    增加samba用户提示Failed to add entry for user
    二叉树
    excel技巧
    mongodb导入json文件
    mongodb导出数据csv格式
    mongoexport导出csv中文乱码
    左连接,结果大于左面的表验证 解释
    plsql 用法和技巧
    对javaNI和NIO理解
    TinyMCE4.x整合教程-Xproer.WordPaster
  • 原文地址:https://www.cnblogs.com/gdsblog/p/7225507.html
Copyright © 2011-2022 走看看