How can I do a LEFT OUTER JOIN using Rails ActiveRecord?

前端 未结 8 1050
终归单人心
终归单人心 2021-02-05 06:42

I don\'t have any ideas. Could you give me any clues (like reference sites). Any help will be appreciated.

Model1: GROUP         


        
相关标签:
8条回答
  • 2021-02-05 07:38

    You can do this in rails 3.x regardless if you are referencing the table or not in a where clause:

    Group.eager_load(:user_group_cmb)
    

    ...and it will perform a left outter join

    0 讨论(0)
  • 2021-02-05 07:44

    The problem with the accepted answer is that it will actually do a LEFT INNER JOIN technically because it won't display entries where the user_group_cmbs. user_id is null (which would be the reason to do a LEFT OUTER JOIN).

    A working solution is to use #references:

    Group.includes(:user_group_cmb).references(:user_group_cmb)
    

    Or the even more convenient #eager_load:

    Group.eager_load(:user_group_cmb)
    

    Read the more detailed explanation here.

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