Joined tables overwrite columns with the same name
See original GitHub issueCame upon this today and it’s causing me quite a headache, I haven’t found a good way of resolving this.
Okay, so take for instance that we create a simple OneToMany join:
var posts = Knex('posts')
.join('comments', 'comments.parent_id', '=', 'posts.id')
.where({ 'posts.id': 1}).select()
.then(function(result){
res.send(result);
});
The results come back as a flat tree. That makes sense, just like a regular SQL return (meaning that if you have 10 comments, you’ll have 10 arrays with data from each comment + a copy of post data); however, if the posts table contains the column “name” and the comments table contains the column “name”, the joined table (comments in this case) will overwrite the parent table (posts). Same goes for dates and a bunch of others.
For instance, if you just query for the post, you may get:
[ {
"id": 1,
"name": "My first post",
"content": "Little johnny went to the woods...",
"date": "1/29/2013",
"category_id": 1
}]
When querying a single comment, you may get the following:
[{
"id": 3
"name": "AntJanus"
"content": "Hi, this is my first comment",
"date": "1/31/2013",
"email": "whatever@whatever.com"
"parent_id": "1"
}]
The resulting join will look like so:
[
{
"id": 3,
"name": "AntJanus",
"content": "Hi, this is my first comment",
"date": "1/31/2013",
"email": "whatever@whatever.com",
"category_id": 1,
"parent_id": 1
},
{
"id": 4,
"name": "Some Other",
"content": "Hi, this is my second comment",
"date": "2/1/2013",
"email": "whatever@whatever.com",
"category_id": 1,
"parent_id": 1
}
]
And it will completely overwrite original name and content of the post.
I haven’t found a way around it with SQL other than using a select statement that aliases each individual column (there’s no way to mass alias in SQL). However, on large and variable tables, this is not really an option.
Issue Analytics
- State:
- Created 10 years ago
- Reactions:2
- Comments:32 (4 by maintainers)
Top GitHub Comments
.options({ nestTables: true}
solve the issue as the result will be each table in a different object.Hey, I’ve ended up here a couple times and thought I would post to let people know what I’ve found.
The
.options({nestTables:true})
doesn’t work in Postgres (it’s a MySQL feature, I believe), but luckily you can get similar functionality using theto_json
tools in Postgres.This is outlined in an issue for
node-postgres
here:Nesting Tables in Node Postgres
Hope this helps if anyone ends up here like I did.