Ruby on rails开发从头来(五十三)- ActiveRecord基础(表关联)

来源:互联网 发布:食人鱼3d知乎 编辑:程序博客网 时间:2024/06/05 18:51

很多程序使用的数据库都包含有多个表,而且通常一些表之间还有关联关系,订单常含有多个条目,而一个条目又关联到一种商品,一个商品可能又属于多个商品分类,一个商品分类里又包含有多个不同的商品。

在数据库中,这些关联表现为使用主键值把表关联起来,也就是外键,但是这属于底层的范畴,我们需要处理Model对象间的关联,而不是数据库中的列和键。如果一个订单含有多个条目,我们需要有办法来维持,处理它们的关系,如果一个条目引用到一种商品,我们或许想这样做:

price = line_item.product.price

而不愿像下面这样麻烦:

product_id = line_item.product_id

product = Product.find(product_id)

price = product.price

Active Record可以帮助我们,作为ORM的一部分,Active Record将低级别的数据库中的外键转换成高级别的对象间的映射。处理了三种基本情况:

-         A表中的一条记录和B表的零条或一条记录相关联。

-         A表中的一条记录和B表的任意多条记录相关联。

-         A表中的任意多条记录和B表的任意多条记录相关联。

 

下面我们来看看怎样创建外键(Foreign Key),我们使用下面的DDL来创建表,它们之间指定了关联:

create table products (

idint not null auto_increment,

titlevarchar(100) not null,

/*. . . */

primary key (id)

);

create table orders (

idint not null auto_increment,

namevarchar(100) not null,

/*... */

primary key (id)

);

create table line_items (

idint not null auto_increment,

product_idint not null,

order_idint not null,

quantityint not null default 0,

unit_pricefloat(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)

);

在上面的DDL中,订单和条目关联,条目又关联到具体的商品。注意这里的命名约定,外键的名字product_id,product是products表的单数形式,然后再加上表的主键名字_id构成外键名。

上面的DDL中,订单和条目是一对多的关系,还有一种是多对多关系,例如,一种商品属于多个商品分类,一个商品分类又含有多种商品。对这种情况,通常我们使用第三个表,叫做结合表,这个表只包含两个要关联的表的id:

create table products (

idint not null auto_increment,

titlevarchar(100) not null,

/*. . . */

primary key (id)

);

create table categories (

idint not null auto_increment,

namevarchar(100) not null,

/*... */

primary key (id)

);

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的约定为两个表名,中间用下划线分开,表名按照字母排序,Rails会自动找到categories_products表将categories表和products链接起来,如果你没有按照约定,那么就要自己声明,以便Rails能够找到它。

原创粉丝点击