当前位置: 首页 > 后端技术 > Node.js

1教你用js操作数据库mysql-orm学习笔记

时间:2023-04-03 23:50:00 Node.js

Node.jsORM-Sequelize基本概述:基于Promise的ORM(对象关系映射),支持多数据库、事务、关联等安装:npmisequelizemysql2-S基本用法:constSequelize=require("sequelize");//建立连接constsequelize=newSequelize("kaikeba","root","admin",{host:"localhost",dialect:"mysql",operatorsAliases:false});//定义模型constFruit=sequelize.define("Fruit",{name:{type:Sequelize.STRING(20),allowNull:false},price:{type:Sequelize.FLOAT,allowNull:false},stock:{type:Sequelize.INTEGER,defaultValue:0}});//同步数据库,force:true会删除已有表Fruit.sync().then(()=>{//添加测试数据returnFruit.create({name:"Banana",price:3.5});}).then(()=>{//查询Fruit.findAll().then(fruits=>{console.log(JSON.stringify(fruits));});});什么是强制同步?如何使用?(现有表会被重置)Fruit.sync({force:true})表默认生成时间戳,如何去掉?constFruit=sequelize.define("Fruit",{},{timestamps:false});指定表名:freezeTableName:true或tableName:'xxx'设置前者使用modelName作为表名;设置后者按下它的值用作表名。Getters&Setters的作用是什么?:可用于定义映射到数据库字段的伪属性或受保护属性//定义为属性名称的一部分:{type:Sequelize.STRING,allowNull:false,get(){constfname=this.getDataValue("name");constprice=this.getDataValue("价格");conststock=this.getDataValue("股票");return`${fname}(price:¥${price}stock:${stock}kg)`;}}//定义为模型选项{getterMethods:{amount(){returnthis.getDataValue("stock")+"kg";}},setterMethods:{amount(val){constidx=val.indexOf('kg');constv=val.slice(0,idx);this.setDataValue('股票',v);}}}//触发setterMethodsFruit.findAll().then(fruits=>{console.log(JSON.stringify(fruits));//修改数量,触发setterMethodsfruits[0].amount='150kg';fruits[0].保存();});如何验证?:您可以通过验证函数验证模型字段的格式和内容,验证会在创建、更新和保存时自动运行price:{validate:{isFloat:{msg:"Pleaseenteranumberforthepricefield"},min:{args:[0],msg:"价格字段必须大于0"}}},stock:{validate:{isNumeric:{msg:"请为股票字段输入一个数字"}}}如何扩展模型?:您可以添加模型实例方法或类方法来扩展模型//添加类级方法Fruit.classify=function(name){consttropicalFruits=['banana','mango','coconut'];//热带水果returntropicalFruits.包括(姓名)?'热带水果':'其他水果';};//添加实例级方法Fruit.prototype.totalPrice=function(count){return(this.price*count).toFixed(2);};//使用类方法['banana','strawberry'].forEach(f=>console.log(f+'is'+Fruit.classify(f)));//使用实例方法Fruit.找到所有()。then(fruits=>{const[f1]=fruits;console.log(`买5kg${f1.name}需要¥${f1.totalPrice(5)}`);});add,delete,modify,check1increaseret=awaitFruit.create({name:"Banana",price:3.5})2Delete//方法一Fruit.findOne({where:{id:1}}).then(r=>r.destroy());//方法二Fruit.destroy({where:{id:1}}).then(r=>console.log(r));3change//方法一Fruit.findById(1).then(fruit=>{fruit.price=4;fruit.save().then(()=>;console.log('update!!!!'));});//方法2Fruit.update({price:4},{where:{id:1}}).then(r=>{console.log(r);console.log('update!!!!')})4查看op链接(https://www.cnblogs.com/zhaom...)//QueryFruit.findOne({where:{name:"Banana"}}).then(fruit=>{//fruit是第一个匹配项,如果不是,则为nullconsole.log(fruit.get());});//获取数据并总数Fruit.findAndCountAll().then(result=>{console.log(result.count);console.log(result.rows.length);});//查询算子constOp=Sequelize.Op;Fruit.findAll({//where:{price:{[Op.lt()]:4},stock:{[Op.gte()]:100}}where:{price:{[Op.lt]:4,[Op.gt]:2}}}).then(fruits=>{console.log(fruits.length);});//语句Fruit.findAll({//其中:{[Op.or]:[{price:{[Op.lt]:4}},{stock:{[Op.gte]:100}}]}where:{price:{[Op.or]:[{[Op.gt]:3},{[Op.lt]:2}]}}}).then(fruits=>{console.log(fruits[0].get());});//分页Fruit.findAll({offset:0,limit:2,})//排序Fruit.findAll({order:[['price','DESC']],})//聚合setTimeout(()=>{Fruit.max("price").then(max=>{console.log("max",max)})Fruit.sum("price").then(sum=>{console.log("sum",sum);});},500)4-2关联查询关联//1:N关系constPlayer=sequelize.define('player',{name:Sequelize.STRING});constTeam=sequelize.define('team',{name:Sequelize.STRING});//将teamId作为外键添加到Player表中Player.belongsTo(Team);//1方建立关系Team.有很多(玩家);//N端建立关系//同步sequelize.sync({force:true}).then(async()=>{awaitTeam.create({name:'Rocket'});awaitPlayer.bulkCreate([{name:'Harden',teamId:1},{name:'Paul',teamId:1}]);//1-sideassociationqueryconstplayers=awaitPlayer.findAll({include:[Team]});console.log(JSON.stringify(players,null,'\t'));//N端关联查询constteam=awaitTeam.findOne({where:{name:'Rocket'},include:[Player]});console.log(JSON.stringify(team,null,'\t'));});//多对多关系constFruit=sequelize.define("fruit",{name:Sequelize.STRING});const类别=续集ze.define("category",{name:Sequelize.STRING});Fruit.FruitCategory=Fruit.belongsToMany(Category,{through:"FruitCategory"});