我有两张桌子。一个是类别表,另一个是具有类别外键的项目表(一个类别可以有多个项目)
我试图公开以下代码中的所有项目
router.route('/projects')
.get(function(req,res){
//knex('projects').select(['projects.id','projects.name','projects.category_id','categories.name']).innerJoin('categories','projects.category_id','categories.id')
knex.from('projects').innerJoin('categories','projects.category_id','categories.id')
.then(function(collection){
console.log(collection);
res.json({
error:false,
data: collection
})
})
.catch(function(err){
res.json({
error:true,
data:{
message:err.message
}
})
})
})
两个knex语句都返回了类似于下面的截断输出
{
"error": false,
"data": [
{
"id": 1,
"name": "Music",
"category_id": 1,
"created_at": 1458126413858
},
{
"id": 2,
"name": "Science",
"category_id": 2,
"created_at": 1458126413858
}
]
}
但是,原始SQL似乎是正确的
select * from "projects" inner join "categories" on "projects"."category_id" = "categories"."id"
或
select "projects"."id", "projects"."name", "projects"."category_id", "categories"."name" from "projects" inner join "categories" on "projects"."category_id" = "categories"."id"
在sqlite上单独运行上述语句似乎返回整个表结果
knex声明在哪里出错?
供参考,这是架构
项目表
var table = (table) => {
table.increments().primary();
table.string('name');
table.integer('category_id').references('categories.id');
table.timestamp('created_at').defaultTo(Date.now());
}
类别表
var table = (table) => {
table.increments().primary();
table.string('name');
table.timestamp('created_at').defaultTo(Date.now());
}
答案 0 :(得分:1)
通过使用columnNames的别名来解决它,如下所示
knex('projects').select(['projects.id as projectId','projects.name as projectName','projects.category_id','categories.name as categoryName']).innerJoin('categories','projects.category_id','categories.id')