我如何 select knex 上的特定列与连接?
How can I select specific columns on knex with join?
我有一条评论 table,外键引用了作者和发表评论的 post。我正在尝试像这样拉评论:
return knex.table('comments').join('users', 'users.id', '=', 'comments.user_id').where('post_id', id);
我确实得到了指定 post id 的评论,但我也得到了用户列中的所有列,包括他们的电子邮件和密码哈希值:
[
{
"id": 1,
"user_id": 1,
"post_id": 1,
"body": "Some random text.",
"username": "John Doe",
"email": "johndoe@example.com",
"password_hash": "edited"
},
...
]
我想删除电子邮件和 password_hash 列。添加 pluck() 只会呈现一列。如果我向 .pluck() 调用添加更多列,我会得到一个布尔值数组。我怎样才能让它只从用户 table 获取 id 列以及评论 table?
的所有内容
我严重缺乏睡眠,所以出于某种原因我忘记了加入:
getAllComments(id) {
return knex.select([
'comments.id',
'comments.post_id',
'comments.body',
'users.username',
]).from('comments').innerJoin('users', 'users.id', '=', 'comments.user_id')
.where('comments.user_id', '=', id);
},
returns:
[
{
"id": 1,
"post_id": 1,
"body": "Far far away, behind the word mountains, far from the countries Vokalia and Consonantia, there live the blind texts.",
"username": "John Doe"
},
...
]
我有一条评论 table,外键引用了作者和发表评论的 post。我正在尝试像这样拉评论:
return knex.table('comments').join('users', 'users.id', '=', 'comments.user_id').where('post_id', id);
我确实得到了指定 post id 的评论,但我也得到了用户列中的所有列,包括他们的电子邮件和密码哈希值:
[
{
"id": 1,
"user_id": 1,
"post_id": 1,
"body": "Some random text.",
"username": "John Doe",
"email": "johndoe@example.com",
"password_hash": "edited"
},
...
]
我想删除电子邮件和 password_hash 列。添加 pluck() 只会呈现一列。如果我向 .pluck() 调用添加更多列,我会得到一个布尔值数组。我怎样才能让它只从用户 table 获取 id 列以及评论 table?
的所有内容我严重缺乏睡眠,所以出于某种原因我忘记了加入:
getAllComments(id) {
return knex.select([
'comments.id',
'comments.post_id',
'comments.body',
'users.username',
]).from('comments').innerJoin('users', 'users.id', '=', 'comments.user_id')
.where('comments.user_id', '=', id);
},
returns:
[
{
"id": 1,
"post_id": 1,
"body": "Far far away, behind the word mountains, far from the countries Vokalia and Consonantia, there live the blind texts.",
"username": "John Doe"
},
...
]