我需要列出我的应用程序中的所有帖子,然后列出每个帖子的作者姓名。
模型POST
var post= sequelize.define("post", {
id: {
type: DataTypes.UUID,
primaryKey: true
},
type: DataTypes.STRING,
data: DataTypes.JSONB
}, {
tableName: 'document',
paranoid: true
});
型号用户
var user= sequelize.define("user", {
id: {
type: DataTypes.UUID,
primaryKey: true
},
type: DataTypes.STRING,
data: DataTypes.JSONB
}, {
tableName: 'document',
paranoid: true
});
注意:它们都在表'document'
中每条记录的一个例子
发表
id: 97aabb70-5fef-11e6-8a8c-f783538c5572
type: 'post'
data: {
"author": "cd418bf0-5ff5-11e6-be58-bb65628b456c"
"message": 'Hello World!'
}
用户
id: cd418bf0-5ff5-11e6-be58-bb65628b456c
data: {
"name": "foo"
}
所以,我需要做的是在帖子上使用findAndCount并检索他们的作者(用户)。
外键是“data”列中的属性“author”
尝试
post.hasOne(user, {
foreignKey: "author"
}
options.include = {all: true};
post.findAndCount(options) //ERROR here
收到错误
column user.author does not exist
由sequelize创建的SQL语句
SELECT count("post"."id") AS "count"
FROM "document" AS "post"
LEFT OUTER JOIN "document" AS "user" ON "post"."id" = "user"."author"
理想的SQL语句sequelize应该创建
SELECT count("post"."id") AS "count"
FROM "document" AS "post"
LEFT OUTER JOIN "document" AS "user" ON "post"."id" = ("user"."data"#>>'{author}')::uuid
注意:Post.data中作者的ID存储为TEXT,因此我需要将其转换为uuid才能正常工作
我已经尝试了很多方法来实现这一点,比如
foreignKey: '\"data\".\'{author}\''
foreignKey: '\"data\".\'{author}\'::uuid'
但它们都不适合我。
我该如何实现?