zoukankan      html  css  js  c++  java
  • Ruby on rails开发从头来(五十三) ActiveRecord基础(表关联)

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

    在数据库中,这些关联表现为使用主键值把表关联起来,也就是外键,但是这属于底层的范畴,我们需要处理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 (

    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)

    );

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

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

    create table products (

    id int not null auto_increment,

    title varchar(100) not null,

    /* . . . */

    primary key (id)

    );

    create table categories (

    id int not null auto_increment,

    name varchar(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能够找到它。
  • 相关阅读:
    Shell 批量搜索关键词并保存结果到文件中(数组、循环)
    解决tensorflow的Session Exception问题
    解决h5py的FutureWarning问题
    【转】Ubuntu16.04安装WPS
    [Linux] 随机切分文件内容
    [Python] 动态函数调用(通过函数名)
    [Python] dict字典的浅复制与深复制
    基于sklearn进行文本向量化
    Asp.Net MVC SingleServiceResolver类剖析
    Asp.Net MVC 高级特性(附带源码剖析)
  • 原文地址:https://www.cnblogs.com/dahuzizyd/p/ruby_rails_study.html
Copyright © 2011-2022 走看看