sequelize.query 原始查询

由于在很多情况下执行原始/已经准备好的SQL查询更加容易,因此可以使用该sequelize.query方法。

默认情况下,该函数将返回两个参数-一个结果数组和一个包含元数据的对象(例如,受影响的行数等)。请注意,由于这是原始查询,因此元数据特定于方言。一些方言将元数据“返回”到结果对象内(作为数组的属性)。但是,将始终返回两个参数,但对于MSSQL和MySQL,它将是对同一对象的两个引用。

const [results, metadata] = await sequelize.query("UPDATE users SET y = 42 WHERE x = 12");
// Results will be an empty array and metadata will contain the number of affected rows.

在不需要访问元数据的情况下,可以传入查询类型以告诉序列化如何格式化结果。例如,对于一个简单的选择查询,您可以执行以下操作:

const { QueryTypes } = require('sequelize');
const users = await sequelize.query("SELECT * FROM `users`", { type: QueryTypes.SELECT });
// We didn't need to destructure the result here - the results were returned directly

还有其他几种查询类型。查阅源代码以获取详细信息

 

第二种选择是模型。如果您传递模型,则返回的数据将是该模型的实例。

// Callee is the model definition. This allows you to easily map a query to a predefined model
const projects = await sequelize.query('SELECT * FROM projects', {
  model: Projects,
  mapToModel: true // pass true here if you have any mapped fields
});
// Each element of `projects` is now an instance of Project

请参阅查询API参考中的更多选项。一些例子:

const { QueryTypes } = require('sequelize');
await sequelize.query('SELECT 1', {
  // A function (or false) for logging your queries
  // Will get called for every SQL query that gets sent
  // to the server.
  logging: console.log,
 
  // If plain is true, then sequelize will only return the first
  // record of the result set. In case of false it will return all records.
  plain: false,
 
  // Set this to true if you don't have a model definition for your query.
  raw: false,
 
  // The type of query you are executing. The query type affects how results are formatted before they are passed back.
  type: QueryTypes.SELECT
});
 
// Note the second argument being null!
// Even if we declared a callee here, the raw: true would
// supersede and return a raw object.
console.log(await sequelize.query('SELECT * FROM projects', { raw: true }));

“点分”属性和nest选项

如果表的属性名称包含点,则通过设置nest: true选项,结果对象可以成为嵌套对象。这是通过使用dottie.js来实现的。见下文:

  • 没有nest: true

const { QueryTypes } = require('sequelize');
const records = await sequelize.query('select 1 as `foo.bar.baz`', {
  type: QueryTypes.SELECT
});
console.log(JSON.stringify(records[0], null, 2));
{
  "foo.bar.baz": 1
}

nest: true

const { QueryTypes } = require('sequelize');
const records = await sequelize.query('select 1 as `foo.bar.baz`', {
  nest: true,
  type: QueryTypes.SELECT
});
console.log(JSON.stringify(records[0], null, 2));
{
  "foo": {
    "bar": {
      "baz": 1
    }
  }
}

替代品

查询中的替换可以通过两种不同的方式来完成,或者使用命名参数(以开头:),也可以使用以表示的未命名参数?。替换项在options对象中传递。

  • 如果传递了数组,?则将按照它们在数组中出现的顺序进行替换
  • 如果传递了一个对象,:key则将替换为该对象中的键。如果对象包含在查询中找不到的键,反之亦然,则将引发异常。
const { QueryTypes } = require('sequelize');
 
await sequelize.query(
  'SELECT * FROM projects WHERE status = ?',
  {
    replacements: ['active'],
    type: QueryTypes.SELECT
  }
);
 
await sequelize.query(
  'SELECT * FROM projects WHERE status = :status',
  {
    replacements: { status: 'active' },
    type: QueryTypes.SELECT
  }
);

数组替换将被自动处理,以下查询将搜索状态与值数组匹配的项目。

const { QueryTypes } = require('sequelize');
 
await sequelize.query(
  'SELECT * FROM projects WHERE status IN(:status)',
  {
    replacements: { status: ['active', 'inactive'] },
    type: QueryTypes.SELECT
  }
);

要使用通配符运算符%,请将其附加到您的替代字符中。以下查询将用户名称以“ ben”开头的用户进行匹配。

const { QueryTypes } = require('sequelize');
 
await sequelize.query(
  'SELECT * FROM users WHERE name LIKE :search_name',
  {
    replacements: { search_name: 'ben%' },
    type: QueryTypes.SELECT
  }
);

绑定参数

绑定参数就像替换。在查询发送到数据库之前,通过替换将替换内容转义并插入到查询中,而将绑定参数发送到SQL查询文本之外的数据库中,则将绑定参数发送到数据库中。查询可以具有绑定参数或替换参数。绑定参数由$ 1,$ 2,...(数字)或$ key(字母数字)引用。这与方言无关。

  • 如果传递了数组,$1则绑定到数组(bind[0])中的第一个元素
  • 如果传递了一个对象,$key则绑定到object['key']。每个键必须以非数字字符开头。$1不是有效的密钥,即使object['1']存在也是如此。
  • 无论哪种情况,$$都可以用来转义文字$符号。

数组或对象必须包含所有绑定值,否则Sequelize将引发异常。这甚至适用于数据库可能忽略绑定参数的情况。

数据库可能对此增加了更多限制。绑定参数不能是SQL关键字,也不能是表名或列名。在带引号的文本或数据中也将忽略它们。在PostgreSQL中,如果无法从context推断出类型,可能还需要对它们进行类型转换$1::varchar

const { QueryTypes } = require('sequelize');
 
await sequelize.query(
  'SELECT *, "text with literal $$1 and literal $$status" as t FROM projects WHERE status = $1',
  {
    bind: ['active'],
    type: QueryTypes.SELECT
  }
);
 
await sequelize.query(
  'SELECT *, "text with literal $$1 and literal $$status" as t FROM projects WHERE status = $status',
  {
    bind: { status: 'active' },
    type: QueryTypes.SELECT
  }
);

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值