Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
226 views
in Technique[技术] by (71.8m points)

mysql - has_many through doesn't work when using same table

I have a model FamilyService. In the model I have these associations:

belongs_to :family
has_many :balance_histories, :through => :family
has_many :balances, :through => :family

Executing this command: FamilyService.where("families.id > 90000").joins(:balances) works fine. I get:

SELECT families_services.*
FROM families_services
INNER JOIN families ON families.id = families_services.family_id
INNER JOIN balances ON balances.family_id = families.id
WHERE (families.id > 90000)

Also, executing this query: FamilyService.where("families.id > 90000").joins(:balance_histories) gives me this:

SELECT families_services.*
FROM families_services
INNER JOIN families ON families.id = families_services.family_id
INNER JOIN balance_histories ON balance_histories.family_id = families.id
WHERE (families.id > 90000)

Great!

But when trying to do: FamilyService.where("families.id > 90000").joins(:balances, :balance_histories). I get:

SELECT families_services.*
FROM families_services
INNER JOIN families ON families.id = families_services.family_id
INNER JOIN balances ON balances.family_id = families.id
INNER JOIN families families_families_services_join ON families_families_services_join.id = families_services.family_id
INNER JOIN balance_histories ON balance_histories.family_id = families_families_services_join.id
WHERE (families.id > 90000)

Which is wrong (families families_families_services_join ON families_families_services_join.id). How to fix?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

The generated query is actually correct. The line

INNER JOIN families families_families_services_join ON ...

is just temporarily assigning the name families_families_services_join to the table families so the query is clearer.

You can, however, simplify the query by specifying your joins query as,

FamilyService.where("families.id > 90000").joins(family: [:balances, :balance_histories])

This will generate something like

SELECT families_services.*
FROM families_services
INNER JOIN families ON families.id = families_services.family_id
INNER JOIN balances ON balances.family_id = families.id
INNER JOIN balance_histories ON balance_histories.family_id = families.id
WHERE (families.id > 90000)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...