与一个表的双重关系合并为一个

时间:2017-04-06 12:42:47

标签: sql postgresql sequelize.js

我会尝试简化我的例子。我有一个名为friendship的表格,与user有两个关系(我们称之为user1user2)。我想找一个按字母顺序排列的朋友列表。我可以在user1user2中显示。我能知道的唯一方法是使用工会:

SELECT f.*
FROM
    (SELECT "user1"."name" AS "name"
    FROM "friendship" AS "friendship" LEFT JOIN "user" AS "user1"
    ON "friendship"."user1_id" = "requestedUser"."id" 
    AND "user1"."id" != 'me'
    WHERE ("friendship"."user2_id" = 'me')

    UNION

    SELECT "user2"."name" AS "name"
    FROM "friendship" AS "friendship"
        LEFT JOIN "user" AS "user2" 
        ON "friendship"."user2_id" = "user2"."id" 
        AND "user2"."id" != 'me'
    WHERE ("friendship"."user1_id" = 'me')
    ) AS f
ORDER BY "name"
LIMIT ?;

有没有更简单的方法?或者也许有可能在单一的SELECT中做到这一点?你知道sequelize怎么做?

1 个答案:

答案 0 :(得分:0)

在Sequelize中,你应该可以user.getFriends()来吸引所有用户朋友。如果您将关联别名为outboundinbound,则为user.getInbound()user.getOutbound()

Sequelize会自动在允许您获取关联模型的实例上创建和命名方法。