【问题标题】:Deal with foreign keys处理外键
【发布时间】:2013-12-28 03:18:32
【问题描述】:

我找到了一种在 Play 中定义主键的方法:

case class User(id: Pk[Long], name: String)

但我没有找到任何处理外键的方法。有没有或者我必须将它用作普通字段?

【问题讨论】:

  • 告诉我们您正在使用什么数据库库。事实上,您的问题没有为任何人提供准确回答的足够背景。
  • @Dylan,我正在使用 anorm + postgresql。

标签: scala playframework postgresql-9.2 playframework-2.2 anorm


【解决方案1】:

您可以将其视为普通字段。

顺便说一下,您可以查看示例播放!框架应用。您可以在 Play 中找到它们!在文件夹“样本”中分发。例如,检查计算机数据库项目。数据库中有外键,但在代码中它们被视为普通字段。

进化:

create table company (
  id                        bigint not null,
  name                      varchar(255) not null,
  constraint pk_company primary key (id))
;


 create table computer (
  id                        bigint not null,
  name                      varchar(255) not null,
  introduced                timestamp,
  discontinued              timestamp,
  company_id                bigint,
  constraint pk_computer primary key (id))
;
alter table computer add constraint fk_computer_company_1 foreign key (company_id) references company (id) on delete restrict on update restrict;

代码:

case class Computer(id: Pk[Long] = NotAssigned, name: String, introduced: Option[Date], discontinued: Option[Date], companyId: Option[Long])

【讨论】:

  • 为什么使用 bigint 而不是 serial 或 bigserial?
  • 我想您可以在 company.id 和 computer.id 字段上使用 serial/bigserial 而不是 bigint,但不能在 computer.company_id 字段上使用(这会导致错误)。
  • 为什么使用 bigint 而不是 serial 或 bigserial?
猜你喜欢
  • 2011-01-06
  • 2021-12-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-11-26
  • 2014-09-17
  • 1970-01-01
相关资源
最近更新 更多