LoginSignup
0
0

More than 1 year has passed since last update.

sequelizeでよく使う取得方法

Posted at

model/seed

sequelize sequelize-cli

model操作

const sync = require("../models").sync;
// DBを書き換える際に生合成を保つために交通整理するよう伝える
// コードからDB構成を変更する時に必要?
await sync()
// CRUD

// create (buildとsaveが一緒になってる)
const usre = await User.create({ 
  name: "tee",
  password: "password"
})


// read 別で詳しく解説
User.findAll()
User.findByPk(1)

// update 2通りある。 こっちが好き
const user = await User.findByPk(req.params.id)
user.name = req.body.name
user.email = req.body.email
await user.save()

// delete 2通りある こっちが好き
const user = await User.findByPk(req.params.id)
await user.destory()
// オペレーター dataの検索に用いる
const { Op } = require('sequelize');

// 全て取得
User.findAll()

// 特定の条件で取得
User.findAll( { where: {id: 1} })

// Opで検索 idが3以下のもの
User.findAll({ where: { id: { [Op.lte]:3 } } })

// like検索 (カレーを含むものを取得) '%'変数'%'で埋め込む
User.findAll({ where: { name: { [Op.like]:'%カレー%' } } })

// AND条件 (未成年を検索)
User.findAll({ where: { age: { [Op.gte]:0, [Op.lte]:18 } } })

// 複数fieldでAND (名前に雨が入っていて emailにteeが入っているユーザ)
User.findAll({ where: { name: {[Op.like]:'%雨%'}, mail: {[Op.like]:'%tee%'} } })

// OR条件
User.findAll({ where: { [Op.or]:[{name: {[Op.like]:'%雨%'}, {mail: {[Op.like]:'%tee%'}}] } })
// idで検索
User.findByPk(1)

// 条件を満たす最初のデータを取得
User.findOne({ where: { id: 1 } })
eq =
ne !=
lt <
lte <=
gt >
gte >=
like like
ilike ilike

Modelとmigration作成

# カラムの間にスペースを空けるとエラーになる
npx sequelize-cli model:generate --name User --attributes name:string,email:string,password:string

# 内容記述

# migration実行 --env以降省略可能
npx sequelize-cli db:migrate --env development

# 名前を指定して
npx sequelize db:migrate:undo --name

# rollback
npx sequelize db:migrate:undo
'use strict';
module.exports = {
  async up(queryInterface, Sequelize) {
    await queryInterface.createTable('Users', {
      id: {
        allowNull: false,
        autoIncrement: true,
        primaryKey: true,
        type: Sequelize.INTEGER
      },
      name: {
        type: Sequelize.STRING
      },
      pass: {
        type: Sequelize.INTEGER
      },
      createdAt: {
        allowNull: false,
        type: Sequelize.DATE
      },
      updatedAt: {
        allowNull: false,
        type: Sequelize.DATE
      }
    });
  },
  async down(queryInterface, Sequelize) {
    await queryInterface.dropTable('Users');
  }
};

validation

// validationを付与する場合通らなかった婆愛errを吐く可能性があるので、
// errをapi側で用意する

// modelを変更する
User.init(
    {
      name: {
        type: DataTypes.STRING,
        allowNull: false,
        validate: {
          notNull: {
            // trueの部分をこのようにするとメッセージを変更できる
            msg: "名前は必ず入力してください"
          }
        }
      },
      pass: {
        type: DataTypes.INTEGER,
        allowNull: false,
        validate: {
          notNull: true,
          isInt: true
        }
      },
      email: { 
        type: DataTypes.STRING ,
        allowNull: false,
        validate: {
          notNull: true
        }
      },
    },
// 種類
sample: {
  type: DataTypes.TEXT,
  unique: true,
  isEmail: true,
}

// 下記はvalidationではなくfeildオプションに指定する
// validation定義するところの1つ上
allowNull :false,

公式ドキュメント
学習に使用した書籍366ページ

association

// modelファイルに定義する
// belongsToを指定するModelには対象のmodelIdカラムを用意
static associate(models) {
  // define association here
  User.hasMany(models.Post) // hasMany – 1:many
  Post.belongsTo(models.User) // belongsTo – 1:1
  Hoge.hasOne(models.Hogedash) // hasOne – 1:1
  Hoge.belongToMany(models.Hogedash) // belongsToMany – 1:many
}

association関連の記事

seed

// seedファイルを作成 (seedersフォルダに作成)
npx sequelize-cli seed:generate --name sample-users

// 内容を書く

// 反映
npx sequelize-cli db:seed:all
// idはなくて良いが、日付系は明示する必要がある
"use strict";

module.exports = {
  up: (queryInterface, Sequelize) => {
    return queryInterface.bulkInsert("Users", [
        {
          name: "tee",
          email: "tee@example.com",
          password: "password",
          createdAt: new Date(),
          updatedAt: new Date(),
        },
        {
          name: "baru",
          email: "baru@example.com",
          password: "password",
          createdAt: new Date(),
          updatedAt: new Date(),
        },
        {
          name: "ren",
          email: "ren@example.com",
          password: "password",
          createdAt: new Date(),
          updatedAt: new Date(),
        },
      ],
      {}
    );
  },

  down: (queryInterface, Sequelize) => {
    return queryInterface.bulkDelete("Users", null, {});
  },
};

参考

model関連

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0