我有3张桌子(更多,但现在已经3张了)
我尝试通过以下方式加入这3条信息:
主要查询
let query = knex
.select(this.options.fields)
.modify(addLikes3, this.options)
.modify(addComment, this.options)
.from("project.project")
.groupBy("project.project.id")
.debug()
添加喜欢
let addLikes3 = (queryBuilder, options) => {
if (options.actions.includes("likes")){
queryBuilder
.select(
knex.raw("CASE " +
"WHEN project.like.project_id IS NULL THEN NULL " +
"ELSE array_agg(json_build_object(" +
"'id', project.like.id," +
"'member_id', project.like.member_id" +
")) " +
"END as likes"
))
}
if (options.actions.includes("count_likes")){
queryBuilder
.count("project.like.id as count_likes")
}
if (options.actions.includes("count_likes") || options.actions.includes("likes")){
queryBuilder
.leftJoin("project.like", "project.like.project_id", "project.project.id")
.groupBy("project.like.project_id")
}
};
添加评论
let addComment = (queryBuilder, options) => {
logger.debug("Model : adding comments");
if (options.actions.includes("comments")){
queryBuilder.select(
knex.raw("CASE " +
"WHEN project.comment.project_id IS NULL THEN NULL " +
"ELSE array_agg(json_build_object(" +
"'id', project.comment.id," +
"'content', project.comment.content," +
"'member_id', project.comment.member_id," +
"'created_at',project.comment.created_at" +
")) " +
"END as comments"))
}
if (options.actions.includes("count_comments")){
queryBuilder
.count("project.comment.id as count_comments")
}
if (options.actions.includes("comments") ||
options.actions.includes("count_comments")){
console.log("JHSKHJD");
queryBuilder
.leftJoin("project.comment", "project.comment.project_id", "=", "project.project.id")
.groupBy("project.comment.project_id")
}
};
我的结果是这样重复的:
{
"id": 1,
"likes": [
{
"id": 1,
"member_id": 1
},
{
"id": 1,
"member_id": 1
},
{
"id": 2,
"member_id": 2
},
{
"id": 2,
"member_id": 2
},
{
"id": 3,
"member_id": 3
},
{
"id": 3,
"member_id": 3
}
],
"comments": [
{
"id": 2
},
{
"id": 1
},
{
"id": 2
},
{
"id": 1
},
{
"id": 2
},
{
"id": 1
}
],
"count_comments": "6"
},
我尝试了多种解决方案
选择喜欢的子查询。也许我做错了,但没有改变
let likeSubQuery = knex.select(knex.raw("DISTINCT project.like.id, project.like.project_id, project.like.member_id"))
.from("project.like")
.where({"project.like.project_id" : "project.project.id"})
.groupBy("project.like.project_id", "project.like.id")
.as("x");
WITH,但是我无法使其工作,因为它不喜欢我添加更多参数
.with('with_alias', addLikes2 , this.options)