您的位置:首页 > 编程语言 > PHP开发

Yii-数据库操作-多表关联

2014-03-17 12:34 141 查看
目录

一、多表关联的配置

二、多表关联的使用

三、带参数的关联配置

四、静态查询(查询数量)

一、多表关联的配置

注:首先多表关联是在models/xx.php的relations里配置的。而且是互配,但有区别。

格式:

'VarName'=>array('RelationType', 'ClassName', 'ForeignKey',...additional options)

需要弄清楚的几点:

(1),VarName指什么? 
详见下面例2。

(2),RelationType。一共有4种,分别为self::HAS_MANY, self::BELONGS_TO,self::MANY_MANY, self::HAS_ONE。

(3),ClassName。即关联的另一个../model/类名.php。

(4),ForeignKey。谁是谁的外键?

(5),附加条件

重点:常见RelationType有四种

HAS_ONE

HAS_MANY

BELONGS_TO

MANY_TO_MANY



1,基本配置方式

例1,一对多与多对一关系(post和user之间的关系)

(1)models/Post.php

class Post extends CActiveRecord

{

    ......

    publicfunction relations()

    {

       return array(

           'author'=>array(self::BELONGS_TO,'User', 'author_id'),

           'categories'=>array(self::MANY_MANY, 'Category',

               'tbl_post_category(post_id, category_id)'),

       );

    }

}

其中Post与User的关系是BELONGS_TO(多对一)关系,并通过Post的author_id与User关联。

Post中author_id是外键,关联到User中。

注:此处的VarName是author,一个对象。

(2)models/User.php

class User extends CActiveRecord

{

    ......

    publicfunction relations()

    {

       return array(

           'posts'=>array(self::HAS_MANY, 'Post','author_id'),

           'profile'=>array(self::HAS_ONE, 'Profile', 'owner_id'),

       );

    }

}

对于User,与Post的关系是属于HAS_MANY(一对多)关系。并通过Post的author_id与Post关联。

例2,多对多关系

在FailParts.php中

 'Users' => array(self::MANY_MANY, 'User','fail_parts_user(fail_parts_id,user_id)'), 

在User.php中

'FailParts' => array(self::MANY_MANY, 'FailParts','fail_parts_user(user_id, fail_parts_id)'),

由于两者是多对多关系,所以要用Users,而不是User;要用FailParts,而不是FailPart。

此处的Users和FailParts,即为前面的VarName。

例3,一对一关系

比较简单,暂略。

2,关于VarName。

对于类A.php,'VarName'=>array('RelationType', 'B', 'ForeignKey',...additional options)

其中VarName与B基本相同。但未必完全一样。此时就可以在A的views/A/xx.php中通过VarName来访问B及其属性值了。

如果是一对一:A->VarName

如果是多对一:author_name = $post->Author->name;

如果是一对多:$posts  = $author->Post;

如果是多对多:$posts  = $author->Post;//本质是拆成一对多和多对一

foreach($posts as $u){

   $_tmp_titles[] = $u ->title;

}

titleStr = implode(', ', $_tmp_titles);

二、多表关联的使用

常常在controllers里

1,延时加载

(1)多对一

$post = Post::model()->findByPk(10);

$author = $post->author;

批注:此处本质是一对一。

(2)一对多

$user = User::model()->findByPk(10);

$posts = $user->posts;

(3)多对多

需要重点注意:两个id有先后关系。

站在$repairInfo实例的角度,关联关系必须是

'FailParts' => array(self::MANY_MANY, 'FailParts','repair_mapping(repair_info_id,fail_parts_id)'),

而站在$failParts实例的角度,则关联关系变为

'RepairInfos' => array(self::MANY_MANY, 'RepairInfo','repair_mapping(fail_parts_id, repair_info_id)'),

而前面也已经指出,不需要双方都配置,只需需要的一方设置即可。

之前曾使用过的笨方法:

$fails = $repairInfo->FailParts;//在$repairInfo中使用

 

$id = $repairInfo->id;

$maps = RepairMapping::model()->findAll("repair_info_id =$id");

$f_ids = array();

foreach($maps as $map){

   array_push($f_ids, $maps[0]->fail_parts_id);

 }

$f_idsStr = implode(',',$f_ids);

$fails = FailParts::model()->findAll("id IN ($f_idsStr)");

2,主动加载——with

(1)一对多

(2)多对多

$posts = Post::model()->('author')->findAll();

例子:

User.php

//查询一个机房$idc_id的所有用户

function getAdminedUsersByIdc($idc_id){

  $c = new CDbCriteria();

  $c->join = "JOIN idc_user ont.id=idc_user.user_id";

  $c->condition ="idc_user.idc_id=$idc_id";

  returnUser::model()->with('Idcs')->findAll($c);

}

//规则中配置

'Idcs' => array(self::MANY_MANY, 'Idc', 'idc_user(user_id,idc_id)'),

批注:没有with('Idcs'),执行后的结果也一样。只不过不再是eager loading。

三、带参数的关联配置

常见的条件有

1,condition     按某个表的某个字段加过滤条件

例如:

//在User的model里定义,如下关联关系

'doingOutsources' => array(self::MANY_MANY, 'Outsource','outsource_user(user_id, outsource_id)',

     'condition' => "doingOutsources.status_id IN(" .Status::ASSIGNED . "," . Status::STARTED ."," . Status::REJECTED.")"),

//结论:condition是array里指定model的一个字段。

显然,doingOutsources是真实数据表Outsource的别名,所以在condition中可以使用doingOutsources.status_id,当然也可以使用Outsource.status_id。另本表名user的默认别名是t。

2,order            按某个表的某个字段升序或降序

//在RepairInfo的model里定义,如下关联关系

'WorkSheet'  => array(self::HAS_MANY,'WorkSheet', 'repair_info_id', order => 'created_atdesc'),

//调用

$worksheets = $repair_info->WorkSheet;//此时$worksheets是按降序排列

//结论:order是array里指定model的一个字段。

with

joinType

select

params

on

alias

together

group

having

index

还有用于lazy loading的

limit       只取5个或10个

offset

through

官方手册

'posts'=>array(self::HAS_MANY, 'post','author_id',    'order'=>'posts.create_time DESC','with'=>'categories'),

四、静态查询(仅用于HAS_MANY和MANY_MANY)

关键字:self:STAT

1,基本用法。例如,

class Post extends CActiveRecord

{

    ......

    publicfunction relations()

    {

       return array(

           'commentCount'=>array(self::STAT,'Comment', 'post_id'),

           'categoryCount'=>array(self::STAT,'Category','post_category(post_id,category_id)');

       );

    }

}

2,静态查询也支持上面的各种条件查询



'doingOutsourceCount' => array(self::STAT, 'Outsource','outsource_user(user_id, outsource_id)',

                            'condition'=> "outsource.status_id IN(" . Status::ASSIGNED . "," .Status::STARTED ."," . Status::REJECTED
.")"),

其他查询还包括

condition  使用较多

order

select

defaultValue

params

group

having

3,静态查询的加载方式

可以使用lazy loading方式

$post->commentCount.

也可以使用eager loading方式

$posts = Post::model()->with('commentCount','categoryCount')->findAll();

注with中字符串一定是别名。

两者的性能比较:

如果需要取所有post的所有comment,前者需要2N+1次查询,而后者只有一次。两者的选择视情况而定。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: