好的,所以我一直在嘗試搜索 Mikro-ORM 的檔案以查找如何傳入本機 sql 查詢引數,但我什么也沒找到。在稍微玩了一下代碼之后,這就是它的樣子,我認為這是正確的,但我收到了這個錯誤
error: SELECT DISTINCT * FROM direct_messages WHERE receiver_id = $1 OR sender_id = $1 ORDER BY sent_at DESC - there is no parameter $1
at Parser.parseErrorMessage (/Users/yonden/Documents/projects/matchup/server/node_modules/pg-protocol/src/parser.ts:369:69)
at Parser.handlePacket (/Users/yonden/Documents/projects/matchup/server/node_modules/pg-protocol/src/parser.ts:188:21)
at Parser.parse (/Users/yonden/Documents/projects/matchup/server/node_modules/pg-protocol/src/parser.ts:103:30)
at Socket.<anonymous> (/Users/yonden/Documents/projects/matchup/server/node_modules/pg-protocol/src/index.ts:7:48)
at Socket.emit (events.js:400:28)
at Socket.emit (domain.js:470:12)
at addChunk (internal/streams/readable.js:290:12)
at readableAddChunk (internal/streams/readable.js:265:9)
at Socket.push (internal/streams/readable.js:204:10)
at TCP.onStreamRead (internal/stream_base_commons.js:188:23) {
length: 94,
severity: 'ERROR',
code: '42P02',
detail: undefined,
hint: undefined,
position: '60',
internalPosition: undefined,
internalQuery: undefined,
where: undefined,
schema: undefined,
table: undefined,
column: undefined,
dataType: undefined,
constraint: undefined,
file: 'parse_expr.c',
line: '907',
routine: 'transformParamRef'
}
我的代碼目前看起來像這樣
@Query(() => String)
async Conversations(@Ctx() { em, userData }: MyContext): Promise<string> {
const connection = em.getConnection();
const queryString = `SELECT DISTINCT * FROM direct_messages WHERE receiver_id = $1 OR sender_id = $1 ORDER BY sent_at DESC`;
return await connection
.execute(queryString, [userData['sub']])
.then((results) => {
console.log(results);
return 'worked';
})
.catch((error) => {
console.log(error);
return 'Failed';
});
}
僅對于某些背景關系,userData['sub'] 是來自 googleOAuth API 的字串型別的用戶 ID。謝謝!
uj5u.com熱心網友回復:
您需要在原始查詢中使用?而不是$1。這就是底層查詢構建器 knex 的作業方式。
const connection = em.getConnection();
const queryString = `SELECT DISTINCT * FROM direct_messages WHERE receiver_id = ? OR sender_id = ? ORDER BY sent_at DESC`;
return await connection
.execute(queryString, [userData['sub'], userData['sub']])
或者,您可以使用 knex 的命名系結,它是類似的(允許在查詢中多次使用一個引數):
// the `em` needs to be typed to `SqlEntityManager` to have the `getKnex` method
const knex = em.getKnex();
const qb = knex.raw('SELECT DISTINCT * FROM direct_messages WHERE receiver_id = :id OR sender_id = :id ORDER BY sent_at DESC', { id: userData['sub'] });
const res = await em.execute(qb);
// ...
或者 MikroORM 查詢構建器的qb.raw()方法只是一個快捷方式em.getKnex().raw():
https://github.com/mikro-orm/mikro-orm/blob/master/tests/QueryBuilder.test.ts#L1314-L1319
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/313910.html
標籤:sql 打字稿 PostgreSQL 微孔
上一篇:如何用CSS隱藏按鈕文本?
下一篇:將路徑作為引數傳遞給函式
