has_many 关系在商业感知上似乎不正确或不合逻辑,需要像belongs_to_many 这样的东西吗?

发布于 2024-08-30 10:35:07 字数 542 浏览 6 评论 0原文

我的情况是这样的。 公司有很多用户,用户可能属于很多公司。 当前的实现如下所示。


  class Company 
    has_many :employments
    has_many :users, :through => :employments
  end

  class Employment 
    belongs_to :company
    belongs_to :user
  end

  class User
    has_many :employments
    has_many :companies, :through => :employments  #This doesn't looks correct
  end

它有效,但“用户拥有许多公司”在逻辑上看起来没有意义。它一定是类似于“属于许多公司”之类的东西。 我需要使用 has_and_belongs_to_many 吗?

有人可以建议表示这些关系的正确方法吗?

My situation is like this.
Company has many users and users may belongs to many companies.
And current implementation is something like below.


  class Company 
    has_many :employments
    has_many :users, :through => :employments
  end

  class Employment 
    belongs_to :company
    belongs_to :user
  end

  class User
    has_many :employments
    has_many :companies, :through => :employments  #This doesn't looks correct
  end

It works, but "user has many companies" doesn't looks logically meaningful. It must be some thing like belongs_to_many companies.
Do I need to use has_and_belongs_to_many?

Can some one please suggest the right way for representing these relationships?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

靑春怀旧 2024-09-06 10:35:07

如果您不打算向 Employment 类添加一些特殊行为,并且您实际上并不需要它,那么您应该更好地使用 has_and_belongs_to_many。这样,它仍然会有一些名为 CompanyUser 的表,但代码中不会有任何这样的类。

添加:
2个对象之间只有3种可能的连接:1对1、1对多和多对多。 Rails 使用 has_*belongs_to 指示这 2 个对象中的哪一个将获得外键。所以:

  • 一对一:

    使用了has_one和belongs_to。具有belongs_to的对象获得FK。

  • 一对多:

    使用了has_many和belongs_to。具有belongs_to的对象获得FK。

  • 多对多:

    has_many[through] 或 has_and_belongs_to_many 在两个对象中都使用。没有人获得 FK,而是使用 ConnectionTable。

所以不存在“belongs_to_many”这样的东西,因为它与“has_many”相同——提供相同的一对多关系。

If you are not going to add some special behaviour to Employment class and you don't really need it, then you should propably better use has_and_belongs_to_many. This way it will still have some table called CompanyUser, but there will not be any such class in the code.

Added:
There are just 3 possbile conections between 2 objects: 1-to-1, 1-to-many and many-to-many. Rails indicates with has_* or belongs_to what of the 2 objects will get a foreign key. So:

  • 1-to-1:

    has_one and belongs_to are used. The object with belongs_to gets the FK.

  • 1-to-many:

    has_many and belongs_to are used. The object with belongs_to gets the FK.

  • many-to-many:

    has_many[through] or has_and_belongs_to_many are used in both objects. No-one gets a FK, instead a ConnectionTable is used.

So there is no such thing as belongs_to_many, because it would be the same as has_many - providing the same relation 1-to-many.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文