How to join on the same table multiple times?

前端 未结 2 427
[愿得一人]
[愿得一人] 2020-12-11 03:37

I\'m querying for the mutual friends of a given two users. The query below should do the trick for the most part and the friendship table should be self-evident, containing

相关标签:
2条回答
  • 2020-12-11 03:54

    I do it with string arguments to joins:

    User.
      joins("INNER JOIN friendships a ON users.id = a.friend_id").
      joins("INNER JOIN friendships b ON users.id = b.friend_id").
      where("a.user_id" => 1, "b.user_id" => 2)
    

    I'm not aware of a higher-level way to do such a join with Active Record.

    0 讨论(0)
  • 2020-12-11 03:59

    Firstly, you should have proper Model Relationship between User & Friendship.

    user model:
     has_many :friendships
    
    friendship model:
     belongs_to :user
    

    with that: you can get activerecords in your iteration like:

    users = User.all
    users.each do |user|
     user.friendships
     .....
    end
    

    Or, by specific user, like:

    user = User.first
    user.friendships #returns association
    
    or 
    
    User.first.friendships
    

    for 2 specific users (given), you can do like:

    User.where(id: [1,2]) #array of user id, then get the friendship record as above.
    

    Hope this helps!

    0 讨论(0)
提交回复
热议问题