2017-04-06 40 views
1

我會盡量簡化我的示例。我有一個名爲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怎麼辦?

回答

0

在Sequelize中你應該可以做到user.getFriends()以獲得所有的用戶朋友。如果您將關聯別名爲outboundinbound,那麼它將是user.getInbound()user.getOutbound()

Sequelize會自動爲允許您獲取關聯模型的實例創建和命名方法。

+0

謝謝。是的,我知道,但這並不能解決我的問題,即我想按兩個關聯中的相同字段對朋友進行排序。 – kasiacode