在 knex 中使用子查询插入默认值
Insert with defaults using subquery in knex
我有这个问题;
knex('metrics').insert(function() {
this.select('metric as name')
.from('stage.metrics as s')
.whereNotExists(function() {
this.select('*')
.from('metrics')
.where('metrics.name', knex.raw('s.metric'))
})
})
table metrics
有两列;一个递增的 ID 和名称。我希望这会插入到名称列中,因为子查询只有一列、标签名称和默认 ID。然而,相反,它抱怨说我提供了一个类型为 character varying for my integer column id 的列。如何明确表示我希望 id 取默认值?
这可以解决问题
knex('metrics').insert(function() {
this
.select([
knex.raw('null::bigint as id'), // or any other type you need (to force using default value you need to pass explicitly null value to insert query)
'metric as name'
])
.from('stage.metrics as s')
.whereNotExists(function() {
this.select('*')
.from('metrics')
.where('metrics.name', knex.raw('s.metric'))
})
})
我知道,看起来有点 hacky。很高兴在 knex API 中看到一些东西,比如(下面的示例是一个提案,而不是一个工作示例)
knex('table_name')
.insert(
['name', 'surname'],
function () {
this.select(['name', 'surname']).from('other_table'))
}
)
产生
insert into table_name (name, surname) select name, surname from other_table;
我不确定这个界面,但你明白了。喜欢显式写入要插入的字段。
我有这个问题;
knex('metrics').insert(function() {
this.select('metric as name')
.from('stage.metrics as s')
.whereNotExists(function() {
this.select('*')
.from('metrics')
.where('metrics.name', knex.raw('s.metric'))
})
})
table metrics
有两列;一个递增的 ID 和名称。我希望这会插入到名称列中,因为子查询只有一列、标签名称和默认 ID。然而,相反,它抱怨说我提供了一个类型为 character varying for my integer column id 的列。如何明确表示我希望 id 取默认值?
这可以解决问题
knex('metrics').insert(function() {
this
.select([
knex.raw('null::bigint as id'), // or any other type you need (to force using default value you need to pass explicitly null value to insert query)
'metric as name'
])
.from('stage.metrics as s')
.whereNotExists(function() {
this.select('*')
.from('metrics')
.where('metrics.name', knex.raw('s.metric'))
})
})
我知道,看起来有点 hacky。很高兴在 knex API 中看到一些东西,比如(下面的示例是一个提案,而不是一个工作示例)
knex('table_name')
.insert(
['name', 'surname'],
function () {
this.select(['name', 'surname']).from('other_table'))
}
)
产生
insert into table_name (name, surname) select name, surname from other_table;
我不确定这个界面,但你明白了。喜欢显式写入要插入的字段。