我会尝试简化我的例子。我有一个名为friendship
的表格,与user
有两个关系(我们称之为user1
和user2
)。我想找一个按字母顺序排列的朋友列表。我可以在user1
或user2
中显示。我能知道的唯一方法是使用工会:
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
怎么做?
答案 0 :(得分:0)
在Sequelize中,你应该可以user.getFriends()
来吸引所有用户朋友。如果您将关联别名为outbound
和inbound
,则为user.getInbound()
和user.getOutbound()
。
Sequelize会自动在允许您获取关联模型的实例上创建和命名方法。