has_and_belongs_to_many vs has_many 通过 [英] has_and_belongs_to_many vs has_many through

查看:38
本文介绍了has_and_belongs_to_many vs has_many 通过的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请解释两者的区别has_and_belongs_to_many 和 has_many 通过关系.何时何地使用哪一种?

Please explain the difference between has_and_belongs_to_many and has_many through relationship. When and where to use which one?

推荐答案

据我所知,has_and_belongs_to_many 为您提供了一个简单的查找表,其中引用了您的两个模型.

As far as I can remember, has_and_belongs_to_many gives you a simple lookup table which references your two models.

例如,

故事可以属于许多类别.类别可以有很多故事.

Stories can belong to many categories. Categories can have many stories.

Categories_Stories Table
story_id | category_id

has_many :through 为您提供了第三个模型,可用于存储不属于任何原始模型的各种其他信息.

has_many :through gives you a third model which can be used to store various other pieces of information which don't belong to either of the original models.

例如

一个人可以订阅很多杂志.杂志可以有很多订阅者.

Person can subscribe to many magazines. Magazines can have many subscribers.

因此,我们可以在中间有一个订阅模型,它为我们提供了与前面示例类似的表,但具有额外的属性.

Thus, we can have a subscription model in the middle, which gives us a similar table to the earlier example, but with additional properties.

Subscriptions Table
person_id | magazine_id | subscription_type | subscription_length | subscription_date 

等等.

这篇关于has_and_belongs_to_many vs has_many 通过的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆