先談增改刪
模型定義
var Task = sequelize.define( 'task', {
title: Sequelize.STRING,
rank: { type: Sequelize.STRING, defaultValue: 3 }
} );
Create
// 創(chuàng)建數(shù)據(jù)庫(kù)中對(duì)象
Task.create( { title: 'foo' } );
// 創(chuàng)建臨時(shí)變量
var task = Task.build( { title: 'very important task' } );
// 將臨時(shí)變量存入數(shù)據(jù)庫(kù)內(nèi), 只保存 title 屬性
task.save( { fields: [ 'title' ] } );
Update
// 在數(shù)據(jù)庫(kù)中更新 task 的 title
task.update( { title: 'a very different title now' } );
// 更新 排名小于1000或者無(wú)排名的 post 的 updateAt 為 null
Post.update( {
updatedAt: null,
}, {
where: {
rank: {
$or: {
$lt: 100,
$eq: null
}
}
}
//// rank < 1000 OR rank IS NULL
} );
Delete
// 刪除 不活躍的 post
Post.destroy( {
where: {
status: 'inactive'
}
} );
Retrieve
// 只選擇相應(yīng)屬性
Model.findAll( {
attributes: [ 'foo', 'bar' ]
} );
// 做聚類(lèi)
Model.findAll( {
attributes: { include: [ [ sequelize.fn( 'COUNT', sequelize.col( 'hats' ) ), 'no_hats' ] ] }
} );
// 除開(kāi)某些屬性
Model.findAll( {
attributes: { exclude: [ 'baz' ] }
} );
// id 查找
Project.findById( 123 ).then();
// 屬性查找
Project.findOne( { where: { title: 'aProject' } } ).then();
// ?
Project.findOne( { where: { title: 'aProject' }, attributes: [ 'id', [ 'name', 'title' ] ] } ).then();
// 找借宵,無(wú)則創(chuàng)建刑然, created 為 boolean
User.findOrCreate( { where: { username: 'kayor' } } ).spread( function ( user, created ) {} );
// 找并且計(jì)數(shù) count 為計(jì)數(shù), rows 為對(duì)象數(shù)組
Project.findAndCountAll( {
where: { title: { $like: 'foo%' } },
offset: 10,
limit: 2
} ).then( function ( result ) {
console.log( result.count );
console.log( result.rows );
} );
// 找出擁有 active profile 的用戶(hù)
User.findAndCountAll( {
include: [
{ model: Profile, where: { active: true } }
],
limit: 3
} );
Project.findAll();
Project.all();
Project.findAll( { where: { name: "a Project" } } );
Project.findAll( { where: [ "id>?", 25 ] } );
Project.findAll( { where: { id: [ 1, 2, 3 ] } } );
Project.findAll( {
where: {
id: {
$and: { a: 5 },
$or: [ { a: 5 }, { a: 6 } ],
$gt: 6,
$gte: 6,
$lt: 10,
$lte: 10,
$ne: 20,
$between: [ 6, 10 ],
$notBetween: [ 6, 10 ],
$in: [ 1, 2 ],
$notIn: [ 1, 2 ],
$like: '%hat'
},
status: { $not: false }
}
} );
//只找十個(gè)
Project.findAll( { limit: 10 } );
// 跳過(guò)前10個(gè)
Project.findAll( { offset: 10 } );
// 跳過(guò)前10暇务,取兩個(gè)
Project.findAll( { offset: 10, limit: 2 } );
// 遞減
Project.findAll( { order: 'title DESC' } );
// 分組
Project.findAll( { group: 'name' } );
// 計(jì)數(shù)
Project.count( { where: [ "id>?", 25 ] } );
// 找最大
Project.max( 'age' );
// 內(nèi)連接找到擁有符合條件工具的用戶(hù)
Post.findAll( {
include: [ {
model: Comment,
as: 'comment_my',
where: { name: { $like: '%ooth%' } }
} ]
} );
// 獲得原數(shù)據(jù)
Post.findOne( { where: { title: 'scut' } } ).then( function ( post ) {
post.title = 'south china university of tecknology';
console.log( post.title ); // 'south china university of tecknology'
post.reload().then( function () {
console.log( post.title ); // 'scut'
} );
} );