将一个或多个表的连接的右侧转换为knex中的数组

问题描述 投票:0回答:1

请帮助我有类似以下的表格提示

ideas = {
  id,
  title,
  abstract,
  background,
  classification,
  technicalfeild,
  tag,
  user_id,
}

和一个表格的想法图像,看起来像这样

idea-images = {
  id,
  idea_id,
  banner,
  image_details
}

他们有一对多的关系。我需要选择所有具有公共标签的想法,然后在idea-image表中找到图像,并将这些图像作为数组附加到该想法,因为该想法可以包含许多图像。这是我的代码

return knex('ideas')
  .where('tag', 'published')
  .rightJoin('idea-images', 'ideas.id', '=', 'idea-images.idea_id')
  .orderBy('ideas.created_at', 'desc');

以及这里将返回的内容

[
  {
    id: 1,
    title: 'blahhh ',
    abstract: ' blahh',
    background: 'blahhh',
    classification: 'consumer product',
    technicalfeild: '',
    description: 'blah....... ',
    summary: '',
    claims: 'blahhhh',
    tag: 'published',
    user_id: 3,
    created_at: 2020-02-21T00:10:43.692Z,
    updated_at: 2020-02-21T00:10:43.692Z,
    idea_id: 2,
    banner: 'Drawing-2',
    image_details: 'blahhh',

  },
  {
    id: 3,
    title: 'blahhh ',
    abstract: ' test',
    background: 'test',
    classification: 'blahhhh',
    technicalfeild: '',
    description: 'test ',
    summary: '',
    claims: 'test',
    tag: 'published',
    user_id: 2,
    created_at: 2020-02-21T00:10:43.692Z,
    updated_at: 2020-02-21T00:10:43.692Z,
    idea_id: 3,
    banner: 'test',
    image_details: 'test',

  },
  {
    id: 4,
    title: 'My new car ',
    abstract: ' test',
    background: 'test',
    classification: 'consumer product',
    technicalfeild: '',
    description: 'test ',
    summary: '',
    claims: 'test',
    tag: 'published',
    user_id: 2,
    created_at: 2020-02-21T00:10:43.692Z,
    updated_at: 2020-02-21T00:10:43.692Z,
    idea_id: 3,
    banner: 'test2',
    image_details: 'test2',

  }
] 

由于某种原因,如果一个创意有2张图片,它将创建一个新创意!我真的不知道如何将图像数据变成一个数组。

express join knex.js
1个回答
0
投票

这是RightJoin所做的,对于每张图像,它将添加idea。尝试LeftJoin,它将为每个创意加入一个图像(与您所做的相反)。

return knex('ideas')
  .where('tag', 'published')
  .leftJoin('idea-images', 'ideas.id', '=', 'idea-images.idea_id')
  .orderBy('ideas.created_at', 'desc');
© www.soinside.com 2019 - 2024. All rights reserved.