ThinkPHP关联模型操作

比如:你要求删除用户的时候,同时删除与用户有关的所有信息。  
  
一对一:   有 (HAS_ONE)     属于 (BELONGS_TO)
      
一对多:   有 (HAS_MANY)   属于 (BELONG_TO)
      
多对多:   (MANY_TO_MANY)

HAS_ONE  HAS_MANY:

表aoli_member



ThinkPHP关联模型操作_第1张图片

表aoli_good

ThinkPHP关联模型操作_第2张图片

MemberModel.class.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

关联查询

class MemberAction extends Action{
    function index(){
        $member=D('member');   
        //关联查询
        $list=$member->relation(true)->select();
        dump($list);
    }   
}
?>

关联插入

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

关联更新

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

关联删除

class MemberAction extends Action{
    function index(){
        $member=D('member');      
        //关联删除
        $list=$member->relation(true)->delete('4');
       
    }   
}
?>

BELONGS_TO:

GoodAction.class.php


class GoodAction extends Action{
    function index(){
        $good=D('good');      
        $list=$good->relation(true)->select();
        dump($list);
    }   
}
?>

GoodModel.class.php


class GoodModel extends RelationModel{
    protected $_link=array(
        'member'=>array(
            'mapping_type'=>BELONGS_TO,
            'foreign_key'=>'uid', 
        ),
    );
}
?>

你可能感兴趣的:(PHP)