我正在尝试联合查询,因为sequelize不支持它,我也想在 sequelize 和 postgresdb 的自定义查询中添加两个自定义/虚拟字段。如果删除自定义/虚拟字段,则查询有效,如果在选项对象上设置hasJoin:false
,查询也将起作用,但字段在返回的对象上分散。
型号:
Post.define('posts', {
"name": { "type": Types.STRING(250), "allowNull": true },
"customField1": {
type: Types.VIRTUAL,
get: function () { return this.setDataValue('"customField1"'); },
},
"customField2": {
type: Types.VIRTUAL,
get: function () { return this.setDataValue('"customField2"'); },
}
});
查询:
const options = {
hasJoin: true,
replacements: [UserID, UserID, limit, offset],
type: sequelize.QueryTypes.SELECT,
model: models.Posts,
include: [
{ model: models.Users },
]
};
const queryString = 'SELECT "post"."ID","post"."createdAt", "post"."name", "user"."username" AS "user.username", "user"."email" AS "user.email", \'false\' as customField1, \'true\' as customField2 FROM "post" LEFT OUTER JOIN "users" AS "user" ON "post"."UserID" = "user"."ID" WHERE "post"."UserID" IN ( SELECT "followID" FROM "followers" WHERE "UserID" = ? ) GROUP BY "post"."ID", "user"."ID" UNION SELECT "post"."ID","post"."createdAt", "post"."name", "user"."username" AS "user.username", "user"."email" AS "user.email", \'true\' as customField1, \'false\' as customField2 FROM "post" LEFT OUTER JOIN "users" AS "user" ON "post"."UserID" = "user"."ID" WHERE "post"."tags" && array(SELECT hashtag::text FROM "followedHashtags" WHERE "UserID" = ? ) GROUP BY "post"."ID", "user"."ID" ORDER BY "createdAt" DESC LIMIT ? OFFSET ? ';
sequelize.Model.$valIDateIncludedElements(options);
posts = await sequelize.query(queryString, options);
如果将hasJoin设置为false,我将得到类似的对象:
[
{
"id": 6,
"name": "new post",
"createdAt": "2018-07-06T02:22:13.188Z",
"userId": 4,
"user.id": 4,
"user.name": "Mas",
"user.surname": "Blazi",
"user.username": "mas",
"user.email": "bettyblaz2i@email.org",
"customField1": "true",
"customField2": "false"
}
]
因此,当我将hasJoin设置为true并删除自定义字段时,用户对象不会像原来那样组合。
[
{
"id": 6,
"name": "new post",
"createdAt": "2018-07-06T02:22:13.188Z",
"userId": 4,
"user":{
"id": 4,
"name": "Mas",
"surname": "Blazi",
"username": "mas",
"email": "bettyblaz2i@email.org"
}
}
]