插入与主键具有相同值的列

发布于 2024-12-08 05:35:26 字数 318 浏览 3 评论 0原文

在 Rails 中可以插入行并将 id 的值分配给特定列,例如,如果我有一个包含 ID 和 LINK 列的表,其中 LINK 链接到同一个表:

ID | LINK
1  |   1
2  |   1
3  |   1

插入第 2 列和第 3 列很容易,但是有什么办法使用单个 INSERT 语句插入第 1 列?

这可以通过 Rails 语法实现还是我需要自定义 SQL(在 PostgreSQL 上)?

[当然,这可以通过 INSERT/UPDATE 来完成,但我需要禁用此表上的更新]

tx 扎哈里杰

is possible in Rails, to insert row and to assign value of id to specific column, e.g. if i have table which have ID and LINK columns where LINK is link to same table:

ID | LINK
1  |   1
2  |   1
3  |   1

Inserting columns 2 and 3 are easy, but is there any way to insert column 1 with single INSERT statement?

Is this possible via rails syntax or i need custom SQL (on PostgreSQL) ?

[Of course, this can be done with INSERT/UPDATE but i need to disable updates on this table]

tx
Zaharije

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

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

发布评论

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

评论(1

素罗衫 2024-12-15 05:35:26

这是一个自连接表。您不需要自己编写 SQL。只需在模型中定义这种关系,如下所示:

class Employee < ActiveRecord::Base
  has_many :subordinates, :class_name => "Employee"
  belongs_to :manager, :class_name => "Employee",
    :foreign_key => "manager_id"  # or what you call LINK
end

此外,链接可能不是一个好的列名称,如果可以的话,尝试选择更具描述性的名称。

This is a self-joining table. You don't need to write the SQL yourself. Just define this relationship in the model like so:

class Employee < ActiveRecord::Base
  has_many :subordinates, :class_name => "Employee"
  belongs_to :manager, :class_name => "Employee",
    :foreign_key => "manager_id"  # or what you call LINK
end

Also, link probably isn't a good column name, try to pick something more descriptive if you can.

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