首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >将一个表到多个表的连接的右侧转换成一个knex中的数组。

将一个表到多个表的连接的右侧转换成一个knex中的数组。
EN

Stack Overflow用户
提问于 2020-02-21 03:27:13
回答 1查看 748关注 0票数 0

请帮我把桌子设计成这样

代码语言:javascript
复制
ideas = {
  id,
  title,
  abstract,
  background,
  classification,
  technicalfeild,
  tag,
  user_id,
}

还有一个桌子上的想法--像这样的图片

代码语言:javascript
复制
idea-images = {
  id,
  idea_id,
  banner,
  image_details
}

他们有一对多的关系。我需要选择所有的想法,有公共标签,并找到图像中的想法-图像表和附加图像作为一个数组的想法,因为想法可以有许多图像。这是我的密码

代码语言:javascript
复制
return knex('ideas')
  .where('tag', 'published')
  .rightJoin('idea-images', 'ideas.id', '=', 'idea-images.idea_id')
  .orderBy('ideas.created_at', 'desc');

在这里,它会回来

代码语言:javascript
复制
[
  {
    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个图像!我真的不知道如何把图像数据变成数组。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2020-02-23 08:22:58

有两个可能的解决方案,

使用https://www.db-fiddle.com/f/74qcRt3siGF2sxT4ykqh9t/1

  • Split的
  1. 使用group_concat,当每个想法都有少量的图像时,该查询看起来就像,分为2个查询,获取想法,然后通过相关的ideas获取所有的图像。

代码语言:javascript
复制
const ideas = await knex('ideas')
  .where('tag', 'published')
  .orderBy('ideas.created_at', 'desc');
const ideaImages = await knex('ideaImages').whereIn('ideaId', ideas.map(idea => idea.id));

mergeData(ideas, ideaImages);
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/60331790

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档