接著我們可以開始寫 CRUD 了
Create
單筆
let data = {
username: 'alincode1',
password: 'mypassword'
}
let newUser = await User.create(data);
多筆
let data = [{
username: 'alincode1',
password: 'mypassword'
},{
username: 'alincode2',
password: 'mypassword'
}]
await User.bulkCreate(data);
Read
取得一筆
let options = {
where: {
username: 'alincode1'
}
};
let user = await User.findOne(options);
let user = await User.findById(1);
取得多筆
let options = {
where: {
username: {
$like: 'alincode'
}
}
};
let users = await User.findAll(options);
$or, $and, $ne, $in, $not, $notIn, $gte, $gt, $lte, $lt, $like, $notLike, $notILike, $between, $notBetween, $overlap, $contains, $contained
Update
let data = {
password: 'mypassword11111111'
}
let options = {
where: {
username = 'alincode1'
}
}
let updateUser = await User.update(data, options);
Delete
destroy
let options = {
where: {
username: {
$like: 'alincode'
}
}
};
let count = await User.destroy(options);
// count 會顯示 2
延伸閱讀