如何在BookshelfJS中使用ID查询?解决Knex逗号分隔ID查询报错
解决Knex查询报错并实现BookshelfJS的ID查询
先来说你的Knex报错问题:
报错原因
你碰到的function regexp_split_to_array(text) does not exist错误,本质是PostgreSQL的regexp_split_to_array函数需要两个必填参数:要拆分的目标字符串,以及作为分隔符的正则表达式。你的代码里只传了student_id,漏掉了逗号分隔符的参数,才触发了这个错误提示。
修正后的Knex代码
另外,因为你的分隔符是固定的逗号,用string_to_array会比正则拆分更高效(不需要正则匹配开销),更推荐用这个函数:
.get(function(req, res) { knex.select('*') .from('exam') // 拆分逗号分隔的student_id为数组,检查目标ID是否在数组内 .whereRaw('? = any(string_to_array(student_id, \',\'))', [req.params.id]) .then(function(rows) { console.log(rows); // res.send(rows); // 记得解开注释给前端返回响应 }) .catch(function(error) { console.log(error); }); });
如果一定要用regexp_split_to_array,补充分隔符参数即可:
.whereRaw('? = any(regexp_split_to_array(student_id, \',\'))', [req.params.id])
在BookshelfJS中实现相同查询
BookshelfJS基于Knex构建,所以你可以直接复用类似的逻辑,也可以用它的语法糖让代码更优雅:
方法1:直接使用whereRaw(和Knex逻辑对齐)
假设你已经定义了Exam模型:
const Exam = bookshelf.Model.extend({ tableName: 'exam' }); // 执行查询 Exam.query(function(qb) { qb.whereRaw('? = any(string_to_array(student_id, \',\'))', [req.params.id]); }) .fetchAll() .then(function(collection) { console.log(collection.toJSON()); }) .catch(function(error) { console.log(error); });
方法2:封装为模型静态方法(方便复用)
把查询逻辑封装到模型里,后续调用会更简洁:
const Exam = bookshelf.Model.extend({ tableName: 'exam' }, { // 静态方法:通过学生ID查询关联考试 findByStudentId: function(studentId) { return this.query(function(qb) { qb.whereRaw('? = any(string_to_array(student_id, \',\'))', [studentId]); }).fetchAll(); } }); // 使用时直接调用方法 Exam.findByStudentId(req.params.id) .then(function(collection) { console.log(collection.toJSON()); }) .catch(function(error) { console.log(error); });
内容的提问来源于stack exchange,提问作者Apurv Chaudhary
相关产品推荐
相关产品推荐

