首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> Java 程式設計 >> Java 相關知識

Ruby on Rails 開發實戰(五十三):ActiveRecord 基礎 - 表關聯

     編輯:Java 相關知識

實際應用的資料庫通常包含多張表且彼此關聯。ActiveRecord 作為 ORM 層,將底層外鍵轉換為高層級的物件導航,讓開發者能撰寫 price = line_item.product.price 而非手動拼湊 SQL。

三種基本關聯情境

  1. A 表一筆記錄關聯 B 表零或一筆(一對一)
  2. A 表一筆記錄關聯 B 表任意多筆(一對多)
  3. A 表任意多筆關聯 B 表任意多筆(多對多)

建立外鍵與命名慣例

以訂單、明細、商品為例:

create table products (
  id int not null auto_increment,
  title varchar(100) not null,
  primary key (id)
);

create table orders (
  id int not null auto_increment,
  name varchar(100) not null,
  primary key (id)
);

create table line_items (
  id int not null auto_increment,
  product_id int not null,
  order_id   int not null,
  quantity   int not null default 0,
  unit_price float(10,2) not null,
  constraint fk_items_product foreign key (product_id) references products(id),
  constraint fk_items_order   foreign key (order_id)   references orders(id),
  primary key (id)
);

命名慣例:外鍵名 = 參照表單數形式 + _id(如 product_id 參照 products 表)。

多對多中間表

商品與分類為多對多,需中間表 categories_products:

create table categories_products (
  product_id  int not null,
  category_id int not null,
  constraint fk_cp_product  foreign key (product_id)  references products(id),
  constraint fk_cp_category foreign key (category_id) references categories(id)
);

中間表命名慣例:兩表名按字母序,底線串接。遵循慣例 Rails 會自動發現;否則需在宣告中指定 :join_table。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved