如何将表列与另一个表关联

发布于 2025-01-10 11:24:51 字数 418 浏览 3 评论 0原文

所以基本上我想知道我需要什么关联来链接我的路由表和员工表。我有一个路由表,其中包含一个员工列(数组类型),其中保存员工 ID。我还有一个员工表,其中包含(名字,姓氏,电话号码)。

has_many :employees,foreign_key: :employees, class_name: :Employee 不起作用并给出错误。有什么想法吗?

给出了这个错误

ActiveRecord::StatementInvalid (PG::UndefinedColumn: ERROR:  column employees.employees does not exist)
LINE 1: SELECT "employees".* FROM "employees" WHERE "employees"."emp...

So basically I like to know what association i need to link my routes table with employees table. I have a routes table with an employees column (array type) which holds employee id's. I also have an employee table that has (first_name, last_name, phone_number).

A has_many :employees, foreign_key: :employees, class_name: :Employee does not work and gives an error. Any ideas?

This error is given

ActiveRecord::StatementInvalid (PG::UndefinedColumn: ERROR:  column employees.employees does not exist)
LINE 1: SELECT "employees".* FROM "employees" WHERE "employees"."emp...

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

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

发布评论

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

评论(1

如此安好 2025-01-17 11:24:51

在这里使用数组列是一个坏主意:

  • 违反了第一范式。
  • 不允许您使用外键来维护引用完整性。
  • 不适用于希望您以合理的方式对数据进行建模的 ActiveRecord 关联。
  • 您需要手动编写查询。

相反,您最可能想要的是自我引用关联

class AddManagerToEmployees < ActiveRecord::Migration[6.1]
  def change
    add_reference :employees, :manager, 
       null: true, 
       foreign_key: { to_table: :employees }
  end
end

class Employee < ApplicationRecord
  belongs_to :manager, 
    class_name: 'Employee'
  has_many   :subordinates, 
    class_name: 'Employee',
    foreign_key: :manager_id
end

如果经理-员工关系应该是多对多,而不是使用连接表的一对多。

Using an array column here is a just bad idea:

  • Violates first normal form.
  • Doesn't let you use foreign keys to maintain referential integrity.
  • Doesn't work with ActiveRecord assocations that expect you to model your data in a sane way.
  • You will need to write queries by hand.

Instead you most likely want is a self-referential assocation:

class AddManagerToEmployees < ActiveRecord::Migration[6.1]
  def change
    add_reference :employees, :manager, 
       null: true, 
       foreign_key: { to_table: :employees }
  end
end

class Employee < ApplicationRecord
  belongs_to :manager, 
    class_name: 'Employee'
  has_many   :subordinates, 
    class_name: 'Employee',
    foreign_key: :manager_id
end

If the manager-employee relation should be many to many instead of one to many use a join table.

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