在knex中,将一对多表连接的右侧转换为数组



请提供帮助我有一些表格创意,看起来像这个

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

和一张看起来像的表格

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

他们有一对多的关系。我需要选择所有有公共标签的想法,在想法图像表中找到图像,并将图像作为数组附加到想法中,因为想法可能有很多图像。这是我的代码

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',
}
] 

出于某种原因,如果这个想法有两个图像,它就会产生一个新的想法!!!我真的不知道如何将图像数据制作成一个数组。

有两种可能的解决方案,

  1. 使用group_concat,适用于每个想法都有少量图像的情况,查询看起来像https://www.db-fiddle.com/f/74qcRt3siGF2sxT4ykqh9t/1

  2. 分为2个查询,获取想法,然后通过相关想法获取所有图像

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);

最新更新