比如:你要求删除用户的时候,同时删除与用户有关的所有信息。
一对一: 有 (HAS_ONE) 属于 (BELONGS_TO)
一对多: 有 (HAS_MANY) 属于 (BELONG_TO)
多对多: (MANY_TO_MANY)
HAS_ONE HAS_MANY:
表aoli_member
表aoli_good
MemberModel.class.php
<?php
class MemberModel extends RelationModel{
protected $_link=array(
‘good‘=>array(
‘mapping_type‘=>HAS_MANY,//HAS_ONE查询出一条
‘class_name‘=>‘good‘,
‘mapping_name‘=>‘good‘,
‘foreign_key‘=>‘uid‘,
‘mapping_fields‘=>array(‘id‘,‘uid‘,‘title‘),
‘as_fields‘=>‘title,id:goodid‘,
//‘condition‘=>‘‘,//筛选条件
//‘foreign_key‘=>‘‘,//外键
//‘mapping_fields‘=>‘‘,//关联字段
//as_fields
),
);
}
?>
MemberAction.class.php
关联查询
<?php
class MemberAction extends Action{
function index(){
$member=D(‘member‘);
//关联查询
$list=$member->relation(true)->select();
dump($list);
}
}
?>
关联插入
<?php
class MemberAction extends Action{
function index(){
$member=D(‘member‘);
//关联插入
$data[‘username‘]=‘bbbbbbb‘;
$data[‘password‘]=‘bbbbbbb‘;
$data[‘good‘]=array(
array(‘title‘=>‘郝杰‘),
array(‘title‘=>‘燕子‘),
);
$list=$member->relation(true)->add($data);
//关联查询
$list=$member->relation(true)->select();
dump($list);
}
}
?>
关联更新
<?php
class MemberAction extends Action{
function index(){
$member=D(‘member‘);
$data[‘username‘]=‘杰天使‘;
$data[‘password‘]=‘jieangel‘;
$data[‘good‘]=array(
array(‘id‘=>1,‘title‘=>‘郝杰‘),
array(‘id‘=>2,‘title‘=>‘燕子‘),
);
//关联更新
$list=$member->relation(true)->where(‘id=1‘)->save($data);
dump($list);
}
}
?>
关联删除
<?php
class MemberAction extends Action{
function index(){
$member=D(‘member‘);
//关联删除
$list=$member->relation(true)->delete(‘4‘);
}
}
?>
BELONGS_TO:
GoodAction.class.php
<?php
class GoodAction extends Action{
function index(){
$good=D(‘good‘);
$list=$good->relation(true)->select();
dump($list);
}
}
?>
GoodModel.class.php
<?php
class GoodModel extends RelationModel{
protected $_link=array(
‘member‘=>array(
‘mapping_type‘=>BELONGS_TO,
‘foreign_key‘=>‘uid‘,
),
);
}
?>
转自http://blog.sina.com.cn/s/blog_7fb1495b0100y5x7.html