demopark / sequelize-docs-zh-cn Goto Github PK
View Code? Open in Web Editor NEWSequelize 文档的中文版本: v7.0.0-alpha.18 | v6.32.0
Home Page: https://demopark.github.io/sequelize-docs-Zh-CN/
License: GNU General Public License v2.0
Sequelize 文档的中文版本: v7.0.0-alpha.18 | v6.32.0
Home Page: https://demopark.github.io/sequelize-docs-Zh-CN/
License: GNU General Public License v2.0
当前使用的 Node.js 版本 (node -v)
v14.15.0
当前使用的 sequelize 版本
(package.json 所指定的版本)
"sequelize": "^5.21.5"
问题描述
(描述出现的或寻求解决的问题)
sequelize是否有一次性批量更新(update)的api,类似bulkCreate的api, 还是说我只能用原生拼接批量更新的sql语句
代码片段
// 相关代码或报错信息
在非托管事务的描述中 :中文原文“非托管事务强制你手动回滚或提交交易”
但是在英文文档中示例代码中,不需要手动commit ,给出的注释说明是说resolve的时候已经commit,reject的时候也没有手动rollback,个人猜测在抛出错误的时候也自动rollback了。下面是英文的例子
return sequelize.transaction({isolationLevel: Sequelize.Transaction.ISOLATION_LEVELS.SERIALIZABLE}, transaction => {
// your transactions
}).then(result => {
// transaction has been committed. Do something after the commit if required.
}).catch(err => {
// do something with the err.
});
为什么我在A表中定义B表的模型——getB,通过A表使用getB提示undefined,但是编辑器却能.(点)出来
I want to migrate the tables in the old database to the new database via sequelize.
However, there is no "FK" defined in my "module", and the new database will have an "FK" constraint error when creating the table ( module.sync({forec: true}) ).
How can I avoid this problem?
And sequlize.STRING corresponds to the VARCHAR type, but to the new database is the NVARCHAR type.
database: MSSQL
sequelize: v4.38.0
当前使用的 Node.js 版本 (node -v)
(可用 node -v 命令 查看)
当前使用的 sequelize 版本
(package.json 所指定的版本)
问题描述
(描述出现的或寻求解决的问题)
使用原始查询后, 执行插入数据命令, 如何返回插入后的自增ID ?
代码片段
// 相关代码或报错信息
这里“ 如果你不需要联结表中的任何内容,则可以显式地为 attributes 参数提供一个空数组,在这种情况下,将不会获取任何内容,甚至不会创建额外的属性:
Foo.findOne({
include: {
model: Bar,
attributes: []
}
}); ”
代码 应改为Foo.findOne({
include: {
model: Bar,
through: {
attributes: []
}
}
});
当前使用的 Node.js 版本 (node -v)
14.16.0
当前使用的 sequelize 版本
"sequelize": "^6.5.0"
问题描述
我现在有两个模型, 它们之间现在没有关联关系,如何才能实现 两个模型的 非等值连接查询
SELECT
e.salary,
g.grade_level
FROM
employees e
JOIN job_grades g ON e.salary BETWEEN g.lowest_sal
AND g.lowest_sal;
代码片段
class employees extends Model {}
employees.init(
{
employee_id: {
type: DataTypes.INTEGER(6),
allowNull: false,
autoIncrement: true,
primaryKey: true
},
first_name: {
type: DataTypes.STRING(20)
},
last_name: {
type: DataTypes.STRING(25)
},
email: {
type: DataTypes.STRING(25)
},
phone_number: {
type: DataTypes.STRING(20)
},
salary: {
type: DataTypes.DOUBLE(10, 2)
},
commission_pct: {
type: DataTypes.DOUBLE(4, 2)
},
manager_id: {
type: DataTypes.INTEGER(6)
},
hiredate: {
type: DataTypes.DATE
}
},
{
sequelize: db,
modelName: "employees",
}
)
class job_grades extends Model {}
job_grades.init(
{
grade_level: {
type: DataTypes.STRING(3),
unique:true
},
lowest_sal: {
type: DataTypes.INTEGER(11)
},
highest_sal: {
type: DataTypes.INTEGER(11)
}
},
{
sequelize: db,
modelName: "job_grade"
}
)
job_grades.removeAttribute('id')
问题描述:
版本 6.3.4
当用belongsTo关联非主键时,主表总是用自身id,而不用指定的字段
Register.hasOne(User, {as: 'User', foreignKey: 'node'});
User.belongsTo(Register, {targetKey: 'node', foreignKey: 'node'});
两个表node字段名称相同
https://github.com/demopark/sequelize-docs-Zh-CN/blob/master/scopes.md#%E5%85%B3%E8%81%94
举个例子,思考模型Post和Comment。 注释与其他几个模型(图像,视频等)相关联,注释和其他模型之间的关联是多态的,这意味着除了外键 commentable_id 之外,注释还存储一个commentable列。
Post & Comment 应该是帖子和评论吧?
https://github.com/demopark/sequelize-docs-Zh-CN/blob/master/associations.md#%E5%A4%96%E9%94%AE
当您在模型中创建关联时,会自动创建带约束的外键引用。 下面是设置:
const Task = sequelize.define('task', { title: Sequelize.STRING });
const User = sequelize.define('user', { username: Sequelize.STRING });
User.hasMany(Task); // 将会添加 userId 到 Task 模型
Task.belongsTo(User); // 也将会添加 userId 到 Task 模型
现在ts比较火,用的人比较多。
我的话就是用sequelize-typescript来使用sequelize。
所有我感觉如果结合sequelize-typescript一起写中文文档会更好一点
sequelize-typescript地址:https://github.com/RobinBuschmann/sequelize-typescript
sequelize 文档版本
(V6)
sequelize 目录章节
(Model Querying - Basics - 模型查询(基础))
反馈描述
Model.findAll({
attributes: [
'foo',
[sequelize.fn('COUNT', sequelize.col('hats')), 'n_hats']
'bar'
]
});
这里直接使用聚合搜索而不分组不是会报错吗?
当前使用的 Node.js 版本 (node -v)
14.16.1
当前使用的 sequelize 版本
6.0.0
问题描述
使用过python的orm,它可以根据model文件自动生成迁移文件并且迁移
而sequelize好像并不支持这样做,还要手写model文件以及迁移文件 特别是model文件有更改的时候
代码片段
// 相关代码或报错信息
你好,请教一个问题:
这是我的models:
admin的model
这是我project的model
然后本地启动数据库都可以正常使用但是在线上服务器一直报Error: admin.hasMany called with something that's not a subclass of Sequelize.Model 而且指向的就是
Admin.hasMany(models.project, {
foreignKey: 'pro_owner_id',
onDelete: 'cascade',
onUpdate: 'cascade'
});
实在不知道是哪里出问题了,特地来问一下,另外附上我其他model的截图
adminRole(其实是admin的组织结构)
content的model
order的model
project的model
比如前端传一个为 name 的参数,如果为空,则查询全部,不为空则查询所有
Model.findAll({
where: {
name: query.name
}
})
我该如何判断这里query.name
如果为空,就不要有name这个条件?
试过三目运算符置为 undefined
,可是出来的查询条件是 where name=null
还是说我只能把where拎出来,用if-else判断来加入条件,再做查询呢
Constraints & Circularities - 约束 & 循环
有时,你可能希望引用另一个表,而不添加任何约束或关联. 在这种情况下,你可以将引用属性手动添加到架构定义中,并标记它们之间的关系.
架构定义? 感觉这里翻译成“模型定义”会贴切一些。
原文:
Constraints & Circularities
Sometimes you may want to reference another table, without adding any constraints, or associations. In that case you can manually add the reference attributes to your schema definition, and mark the relations between them.
当前使用的 Node.js 版本 (node -v)
(可用 node -v 命令 查看)
当前使用的 sequelize 版本
(package.json 所指定的版本)
问题描述
(描述出现的或寻求解决的问题)
代码片段
// 相关代码或报错信息
查了sequelizze官网没有发现,找github发现有一个 sequelize-redis-cache, 但是却说不支持缓存清除。。。
const User = sequelize.import('../models/rpa_user')
在导入model的时候,报错Path must be a string. Received undefined,可是我明明用的是字符串的路径啊,有没有大佬碰到过这个问题
当前使用的 Node.js 版本 (node -v)
(可用 node -v 命令 查看)
v12.15.0
当前使用的 sequelize 版本
(package.json 所指定的版本)
^5.21.5
问题描述
(描述出现的或寻求解决的问题)
表模型init 以后的 sequelize 以及 sequelize.config.schema 无法动态改变,建议这两个参数允许传入闭包,函数或者方法,以便动态改变当前模型查询操作针对的 数据库连接 或者 schema,从而实现 multi-tenant 多租户业务
请问组合外键要怎么联结, 拜托了.
sequelize.query(sql)查询的结果和用在navigate里面执行同样的sql结果不一样,sequelize.query(sql)查询的结果比实际结果多了两倍
https://github.com/demopark/sequelize-docs-Zh-CN/blob/master/models-definition.md#%E5%AF%BC%E5%85%A5
这部分示例代码
sequelize.import('project', (sequelize, DataTypes) => { class Project extends sequelize.Model {} Project.init({ name: DataTypes.STRING, description: DataTypes.TEXT }, { sequelize }) return Project; })
实际运行会报错,应该使用sequelize.define方法,参考官方示例
https://github.com/sequelize/express-example/tree/master/models
想问下左内连接怎么实现
多对多关系时用belongstomany 如何去除查询结果关系表的数据 如题
attributes 去除 是无效的,文档也没有找到==很绝望 ==求助
默认情况下,Sequelize 将保持连接打开状态,并对所有查询使用相同的连接.
我这边连接走了成功的回调并被挂起 但是10秒左右连接被自动关闭了。请问这是正常的嘛,不是持续保持嘛?
"sequelize": "^5.21.5"
"mysql2": "^2.1.0",
事务回滚后但是事务中的更新删除操作已经生效了
比如数据库里面有 id
,‘name’ 列;
我们在请求接口的时候可能会带上 杂七乱八的参数 ,比如 t = 123123123;
那么到了查询时,一般会把所有的请求参数都去查询
async list(params) { let result = await this.app.model.xxx.findAll({ where : { ...params } }) return result }
;
这时就会把 t
也作为where请求,因为表里没有 t
列,会导致接口报错;
当然代码中是可以仅获取要处理的参数,但是一个个写就很麻烦;请问怎么可以优雅得处理不在预期中的参数呢
如标题描述
创建了 User 模型,以及 Profile 模型。
给 user 模型和 profile 模型添加一对一关系。
在 已有模型 的情况之下,如何能通过 sequelize-cli 的 migrate 功能实现添加关联关系的操作呢?
我想我知道如何在 model 层面里进行关联关系的添加,但是目的是 「版本管理」 嘛。
// app/model/user.js
...
User.associate = () => User.hasOne(Profile);
...
// app/model/profile.js
...
Profile.associate = () => Profile.belongsTo(User);
...
// app/model/user.js
module.exports = app => {
const { STRING} = app.Sequelize;
const User = app.model.define('User', {
id: {
type: INTEGER,
primaryKey: true,
autoIncrement: true,
},
username: STRING,
password: STRING,
});
return User;
};
// app/model/profile.js
module.exports = app => {
const { STRING, INTEGER } = app.Sequelize;
const Profile = app.model.define('Profile', {
description: STRING,
user_id: INTEGER,
});
return Profile;
};
主从配置: https://sequelize.org/master/manual/read-replication.html
集群怎么配置呢?
public async updateConfig(param: IPrinterConfigParam) {
await this.ctx.model.CashierPrinterConfig.sync();
if (param && param.id) {
// 修改
await this.ctx.model.CashierPrinterConfig.upsert({
adminId: param.adminId,
id: param.id,
jsonConfig: param.configJson,
});
} else {
// 新增;
let printerConfig: PlainObject[] = [];
// 查询所有记录
const sqlIntstance = await this.ctx.model.CashierPrinterConfig.findAll({
where: {
adminId: param.adminId,
},
});
if (sqlIntstance) {
sqlIntstance.map(ins => {
let temp = (ins as PlainObject).dataValues;
// 判断当前设备是否已经保存过 deviceNo key
let tempJson = JSON.parse(temp.jsonConfig);
let newJson = JSON.parse(param.configJson);
if (tempJson.deviceNo === newJson.deviceNo && tempJson.key === newJson.key) {
printerConfig.push(temp);
}
});
// 不存在记录
if (printerConfig.length == 0) {
await this.ctx.model.CashierPrinterConfig.create({
adminId: param.adminId,
jsonConfig: param.configJson,
});
} else {
await this.ctx.model.CashierPrinterConfig.upsert({
adminId: param.adminId,
id: printerConfig[0].id,
jsonConfig: param.configJson,
});
}
}
}
}
public async getConfigByAmdinId(adminId: string) {
console.log('getConfigByAmdinId', adminId);
let printerConfig: PlainObject[] = [];
await this.ctx.model.CashierPrinterConfig.sync()
const sqlIntstance = await this.ctx.model.CashierPrinterConfig.findAll({
where: {
adminId,
},
});
if (sqlIntstance) {
sqlIntstance.map(ins => {
let temp = (ins as PlainObject).dataValues;
printerConfig.push({ id: temp.id, config: JSON.parse(temp.jsonConfig) });
});
}
return printerConfig;
}
2018-10-18 09:00:54,334 INFO 15542 egg-sequelize Executed (default): CREATE TABLE IF NOT EXISTS cashier_printer_config
(id
INTEGER auto_increment UNIQUE , admin_id
VARCHAR(20) NOT NULL, json_config
VARCHAR(2000) NOT NULL, modify_time
DATETIME NOT NULL, PRIMARY KEY (id
)) ENGINE=InnoDB;
2018-10-18 09:00:54,336 INFO 15542 egg-sequelize Executed (default): SHOW INDEX FROM cashier_printer_config
2018-10-18 09:00:54,348 INFO 15542 egg-sequelize Executed (default): INSERT INTO cashier_printer_config
(id
,admin_id
,json_config
,modify_time
) VALUES (186,'A882080','{"printMode":"manual","state":1,"deviceType":"wifi"}','2018-10-18 09:00:54') ON DUPLICATE KEY UPDATE admin_id
=VALUES(admin_id
), id
=VALUES(id
), json_config
=VALUES(json_config
), modify_time
=VALUES(modify_time
);
2018-10-18 09:00:54,335 INFO 15541 egg-sequelize Executed (default): CREATE TABLE IF NOT EXISTS cashier_printer_config
(id
INTEGER auto_increment UNIQUE , admin_id
VARCHAR(20) NOT NULL, json_config
VARCHAR(2000) NOT NULL, modify_time
DATETIME NOT NULL, PRIMARY KEY (id
)) ENGINE=InnoDB;
2018-10-18 09:00:54,337 INFO 15541 egg-sequelize Executed (default): SHOW INDEX FROM cashier_printer_config
2018-10-18 09:00:54,339 INFO 15541 egg-sequelize Executed (default): SELECT id
, admin_id
AS adminId
, json_config
AS jsonConfig
, modify_time
AS modifyTime
, modify_time
FROM cashier_printer_config
AS cashier_printer_config
WHERE cashier_printer_config
.admin_id
= 'A882080';
结果还是:
[{"id":186,"config":{"printMode":"auto","state":1,"deviceType":"wifi"}}]
2018-10-18 09:02:49,889 INFO 15542 egg-sequelize Executed (default): CREATE TABLE IF NOT EXISTS cashier_printer_config
(id
INTEGER auto_increment UNIQUE , admin_id
VARCHAR(20) NOT NULL, json_config
VARCHAR(2000) NOT NULL, modify_time
DATETIME NOT NULL, PRIMARY KEY (id
)) ENGINE=InnoDB;
2018-10-18 09:02:49,890 INFO 15542 egg-sequelize Executed (default): SHOW INDEX FROM cashier_printer_config
2018-10-18 09:02:49,892 INFO 15542 egg-sequelize Executed (default): SELECT id
, admin_id
AS adminId
, json_config
AS jsonConfig
, modify_time
AS modifyTime
, modify_time
FROM cashier_printer_config
AS cashier_printer_config
WHERE cashier_printer_config
.admin_id
= 'A882080';
过一会查就正常了
[{"id":186,"config":{"printMode":"manual","state":1,"deviceType":"wifi"}}]
为了研究这一点,我们将思考一个例子,其中有船长和船长,.
船长和船长 ---> 船和船长
原文:
Basics of queries involving associations
In order to study this, we will consider an example in which we have Ships and Captains,
sequelize.query("UPDATE users SET y = 42 WHERE x = 12").spread((results, metadata) => {
// 结果将是一个空数组,元数据将包含受影响的行数。
})
- 疑问一:sequelize.query 这个sequelize 对象是什么对象?? 从哪来??
- 尝试一: 使用定义模型对象(model) 调用query
postmodel.query("select p.*, u.nickname,c.name from posts p left join users u on p.user_id =
u.id left join categories c on p.category_id = c.id limit " + offset + "," + query.size)
.then(result => {
})
错误信息如下:
(node:9056) UnhandledPromiseRejectionWarning: TypeError: postmodel.query is not a function
- 尝试二 : 引入sequelize模块 使用sequelize 调用query方法
//引入模块
var sequelize = require("sequelize");
//调用方法
sequelize.query("select p.*, u.nickname,c.name from posts p left join users u on p.user_id = u.id left join categories c on p.category_id = c.id limit " + offset + "," + query.size)
.then(result => {
})
错误信息如下:
(node:10128) UnhandledPromiseRejectionWarning: TypeError: sequelize.query is not a function
- 请问文档上的sequelize对象 到底是什么对象 从哪来? 文档只有核心使用 并没有对象的来龙去脉
- 要求: 自定义的属性和数据库表中的字段没有关系 即扩展属性
- 目的:查询完数据之后 给前端返回数据时 封装一些 表中没有的字段
- 文档上讲解的 都是定义model时 指定的属性都是数据库有的字段 额外属性 和数据库字段没有关系的属性如何定义呢??
如果允许子查询的话,和分页条件连用会生成子查询语句。然后在子查询语句中会将连接的表的顶级 where 条件放在子查询中,然后会报找不到字段的错误。这个是 sequelize 的 bug
// 设置关系:
Person.hasOne(Person, as 'father');
// 然后查询
Person.findById(123, {include:[{model: Person, as 'father'}]})查询
发现结果没有把father这个模型(实际上就是Peraon)查出来, 请问一下为什么啊?
请问最新的4.28.6 是否还支持
类似于
sequelizer.findAll("user",{where: {name:"zhangsan"}}, function(err, result {
//callback
}))这样的方法
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.