1 jsでデータベースmysql-ormを操作してノートを学ぶ方法を教えます

6107 ワード

Node.js ORM - Sequelize
基本
概要:PromiseベースのORM(Object Relation Mapping)は、複数のデータベース、トランザクション、関連付けなどのインストールをサポートする:npm i sequelize mysql 2-S基本使用:
const Sequelize = require("sequelize");

//     
const sequelize = new Sequelize("kaikeba", "root", "admin", {
    host: "localhost",
    dialect: "mysql",
    operatorsAliases: false
});

//     
const Fruit = 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(() => {
    //           
    return Fruit.create({name: "  ", price: 3.5});
}).then(() => {
    //       
    Fruit.findAll().then(fruits => {
        console.log(JSON.stringify(fruits));
    });
});

強制同期とは何ですか?使用方法(既存のテーブルがリセットされます)
Fruit.sync({force: true})

テーブルはデフォルトでタイムスタンプを生成しますが、どのように削除しますか?
const Fruit = sequelize.define("Fruit", {}, {  timestamps: false });

テーブル名の指定:freezeTable Name:trueまたはtableName:'xxx'
      modelName    ;            。

Getters&Settersはどのような役割を果たしていますか?:擬似属性またはデータベースフィールドへのマッピングに使用できる保護属性
//          
name: {
    type: Sequelize.STRING, 
    allowNull :false, 
    get(){
        const fname = this.getDataValue("name");
        const price = this.getDataValue("price");
        const stock = this.getDataValue("stock");
        return `${fname}(  :¥${price}   :${stock}kg)`;
    }
}

//         
{
    getterMethods:{
        amount()
        {
            return this.getDataValue("stock") + "kg";
        }
    },
    setterMethods:{
        amount(val)
        {
            const idx = val.indexOf('kg');
            const v = val.slice(0, idx);
            this.setDataValue('stock', v);
        }
    }
}

//         setterMethods
Fruit.findAll().then(fruits => {
    console.log(JSON.stringify(fruits));
    //   amount,  setterMethods    
    fruits[0].amount = '150kg';
    fruits[0].save();
});

検証方法:モデルフィールドのフォーマット、内容は検証機能で検証でき、create、update、saveで自動的に実行されます.
price: {
    validate: {
        isFloat: {msg: "         "},
        min: {args: [0], msg:"        0"}
    }
},
stock: {
    validate: {
        isNumeric: {msg: "         "}
    }
}

モデルの拡張方法:モデルインスタンスメソッドまたはクラスメソッド拡張モデルを追加できます
//        
Fruit.classify = function (name) {
    const tropicFruits = ['  ', '  ', '  '];
    //       
    return tropicFruits.includes(name) ? '    ':'    '; };

//         
    Fruit.prototype.totalPrice = function (count) {
        return (this.price * count).toFixed(2);
    };

//      
    ['  ', '  '].forEach(f => console.log(f + ' ' + Fruit.classify(f)));

//       
    Fruit.findAll().then(fruits => {
        const [f1] = fruits;
        console.log(` 5kg${f1.name}  ¥${f1.totalPrice(5)}`);
    });

添削して調べる.
1増加
    ret = await Fruit.create({
        name: "  ",
        price: 3.5
    })

2削除
//   1 
Fruit.findOne({ where: { id: 1 } }).then(r => r.destroy());
 
//   2 
Fruit.destroy({ where: { id: 1 } }).then(r => console.log(r));

3変更
//   1  
Fruit.findById(1).then(fruit => {
    fruit.price = 4;
    fruit.save().then(() => console.log('update!!!!'));
});
//   2 
Fruit.update({price: 4}, {where: {id: 1}}).then(r => {
    console.log(r);
    console.log('update!!!!')
})

4チェックopリンク(https://www.cnblogs.com/zhaom...)
//       
Fruit.findOne({where: {name: "  "}}).then(fruit => {
    // fruit      ,     null    
    console.log(fruit.get());
});

//         
Fruit.findAndCountAll().then(result => {
    console.log(result.count);
    console.log(result.rows.length);
});

//      
const Op = 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({
    // where: { [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  
const Player = sequelize.define('player', {name: Sequelize.STRING});
const Team = sequelize.define('team', {name: Sequelize.STRING});

//    teamId Player     
Player.belongsTo(Team);// 1     
Team.hasMany(Player); // N     

//   
sequelize.sync({force: true}).then(async () => {
    await Team.create({name: '  '});
    await Player.bulkCreate([{name: '  ', teamId: 1}, {name: '  ', teamId: 1}]);
// 1         
    const players = await Player.findAll({include: [Team]});
    console.log(JSON.stringify(players, null, '\t'));
// N       
    const team = await Team.findOne({where: {name: '  '}, include: [Player]});
    console.log(JSON.stringify(team, null, '\t'));
});


//      
const Fruit = sequelize.define("fruit", {name: Sequelize.STRING});
const Category = sequelize.define("category", {name: Sequelize.STRING});
Fruit.FruitCategory = Fruit.belongsToMany(
    Category, {through: "FruitCategory"}
);