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

作者:zccst
目录
一、多表关联的配置
二、多表关联的使用
三、带参数的关联配置
四、静态查询(查询数量)


[size=large][b]一、多表关联的配置[/b][/size]
注:首先多表关联是在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


[img]http://dl.iteye.com/upload/attachment/538689/a67ae289-d007-3f90-b894-cb3c9d477ff1.png[/img]

1,基本配置方式

[b]例1,一对多与多对一关系(post和user之间的关系)[/b]
(1)models/Post.php
class Post extends CActiveRecord
{
......

public function relations()
{
return array(
[color=red]'author'=>array(self::BELONGS_TO, 'User', 'author_id'),[/color]
'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
{
......

public function relations()
{
return array(
[color=red]'posts'=>array(self::HAS_MANY, 'Post', 'author_id'),[/color]
'profile'=>array(self::HAS_ONE, 'Profile', 'owner_id'),
);
}
}

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


[b]例2,多对多关系[/b]
在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。

[b]例3,一对一关系[/b]
比较简单,暂略。

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);


[size=large][b]二、多表关联的使用[/b][/size]
常常在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 on t.id=idc_user.user_id";
$c->condition = "idc_user.idc_id=$idc_id";
return User::model()->with('Idcs')->findAll($c);
}
//规则中配置
'Idcs' => array(self::MANY_MANY, 'Idc', 'idc_user(user_id, idc_id)'),

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

[size=large][b]三、带参数的关联配置[/b][/size]

常见的条件有
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_at desc'),
//调用
$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', [color=red]'order'=>'posts.create_time DESC', 'with'=>'categories'[/color]),

[size=large][b]四、静态查询[/b][/size](仅用于HAS_MANY和MANY_MANY)
关键字:self:STAT
1,基本用法。例如,
class Post extends CActiveRecord
{
......

public function relations()
{
return array(
[color=red]'commentCount'=>array(self::STAT, 'Comment', 'post_id'),
'categoryCount'=>array(self::STAT,'Category','post_category(post_id, category_id)');
[/color]
);
}
}
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('[color=red]commentCount[/color]','[color=red]categoryCount[/color]')->findAll();
注with中字符串一定是别名。

两者的性能比较:
如果需要取所有post的所有comment,前者需要2N+1次查询,而后者只有一次。两者的选择视情况而定。
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值