ThinkPHP 3.2.3 关联模型的使用

关于关联模型

ThinkPHP 3.2.3 的关联模型(手册地址)一般处理关联数据表的 CURD 操作,例如关联读取、关联写入、关联删除等。

 

 

实例

博客管理模块关于博客有 4 张数据表:博客表 crm_blog:

CREATE TABLE `crm_blog` (
  `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `title` varchar(30) NOT NULL DEFAULT '',
  `content` text NOT NULL,
  `time` int(10) unsigned NOT NULL DEFAULT '0',
  `click` smallint(6) unsigned NOT NULL DEFAULT '0',
  `cid` int(10) unsigned NOT NULL,
  `del` tinyint(1) unsigned NOT NULL DEFAULT '0',
  PRIMARY KEY (`id`),
  KEY `cid` (`cid`)
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8

 

属性表 crm_attr:

CREATE TABLE `crm_attr` (
  `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `name` char(10) NOT NULL DEFAULT '',
  `color` char(10) NOT NULL DEFAULT '',
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8

 

博客-属性关联表 crm_blog_attr:

 CREATE TABLE `crm_blog_attr` (
  `bid` int(10) unsigned NOT NULL,
  `aid` int(10) unsigned NOT NULL,
  KEY `bid` (`bid`),
  KEY `aid` (`aid`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8

博客和属性是多对多的关系(MANY_TO_MANY)

 

类别表 crm_cate:

CREATE TABLE `crm_cate` (
  `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `name` char(20) NOT NULL DEFAULT '',
  `pid` int(10) unsigned NOT NULL DEFAULT '0',
  `sort` smallint(6) NOT NULL DEFAULT '100',
  PRIMARY KEY (`id`),
  KEY `pid` (`pid`)
) ENGINE=InnoDB AUTO_INCREMENT=20 DEFAULT CHARSET=utf8

博客相对于类别是一对多(BELONGS_TO)关系,另一个角度类别相对于博客是多对一(HAS_MANY)关系

 

在 Admin 应用下创建 Model 类:./Application/Admin/Model/BlogRelationModel.class.php:

 1 <?php
 2 namespace Admin\Model;
 3 use Think\Model\RelationModel;
 4 
 5 class BlogRelationModel extends RelationModel {
 6     //如果Model文件名是BlogModel.class.php 就不需要定义$tableName
 7     protected $tableName = 'blog';//以blog表为基准表
 8     protected $_link = array(
 9         'attr'=>array(
10             'mapping_name'=>'attr',
11             'mapping_type'=>self::MANY_TO_MANY,//多对多关系
12             'foreign_key'=>'bid',//中间表中blog的id
13             'relation_foreign_key'=>'aid',//中间表中attr的id
14             'relation_table'=>'crm_blog_attr'
15         ),//定义关联表
16         'cate'=>array( //博文和属性 一对多关系
17             'mapping_name'=>'cate',
18             'mapping_type'=>self::BELONGS_TO,//多(cate)关联一(blog)用 HAS_MANY,一(blog)关联多(cate)用BELONGS_TO
19             'foreign_key'=>id, //blog表中的博文id
20             'mapping_fields'=>'name', //只读取name字段
21             'as_fields'=>'name:cate' //把cate表的name字段取出作为主表blod的字段展示并且把name改成cate(避免字段重复)
22         )
23     );
24     
25     //获取博文列表(包括没有删除的博文和回收站的博文,通过参数$type区分)
26     public function get_blogs($type = 0) { //默认是没有删除的博文
27         $field = array('cid','del');
28         $where = array('del'=>$type);
29         return $this->field($field,true)->relation(array('cate','attr'))->where($where)->select();
30     }
31 }

说明:

Line 7:如果 Model 类的文件名是 BlogModel.class.php ,则不需要定义 protected $tableName = 'blog',否则要加上定义,因为实例化 Model 类时找不到 blogrelation 表,只有 blog 表

 

实例化 Model 类

控制器 ./Application/Admin/Controller/BlogController.class.php :

  1 <?php
  2 namespace Admin\Controller;
  3 use Admin\Common\Category;
  4 
  5 class BlogController extends CommonController{
  6     //博文列表
  7     public function index() {
  8         $this->blog = D('BlogRelation')->get_blogs();
  9         $this->display();
 10     }
 11     
 12     //添加博文
 13     public function add_blog() {
 14         //博文分类
 15         $cate = M('cate')->order('sort')->select();
 16         $this->cate = Category::level($cate);//一维数组无限极分类
 17 
 18         //博文属性
 19         $this->attr = M('attr')->select();
 20         
 21         $this->display();
 22     }
 23     
 24     //添加博文表单处理
 25    public function add_blog_handle() {
 26         //echo '<pre>';print_r($_POST);
 27         $data = array(
 28             'title'=>I('title'),
 29             'content'=>I('content'),
 30             'time'=>time(),
 31             'click'=>I('click', 0, 'int'),
 32             'cid'=>I('cid'),
 33         );
 34         
 35         //属性插入到博文-属性中间表 开始
 36         /*if(isset($_POST['aid'])) {
 37             foreach($_POST['aid'] as $v) {
 38                 $data['attr'][] = $v;//attr:关联表名称
 39             }
 40         }*/
 41         
 42         /*D('BlogRelation')->relation(true)->add($data);*/
 43         //$this->display('blog');//用于查看trace信息(config.php定义)
 44         //属性插入到博文-属性中间表 结束
 45         
 46         //自定义插入关联表(不使用关联模型)开始,哪种方法都可以
 47         if($bid = M('blog')->add($data)) {
 48             if(isset($_POST['aid'])) {
 49                 $sql = 'INSERT INTO `'.C('DB_PREFIX').'blog_attr` (bid,aid) VALUES ';
 50                 foreach($_POST['aid'] as $v) {
 51                     $sql .= '('.$bid.','.$v.'),';
 52                 }
 53                 $sql = rtrim($sql,',');
 54                 M()->execute($sql);
 55             }
 56             $this->success('添加成功', U('Admin/Blog/index'));
 57         } else {
 58             $this->error('添加失败');
 59         }
 60         //自定义插入关联表(不使用关联模型)结束
 61         
 62     }
 63     
 64     
 65     //删除到回收站/还原
 66     public function to_recycle_bin () {
 67         $id = (int)$_GET['id'];
 68         $type = (int)$_GET['type'];
 69         $update = array(
 70             'id'=>$id,
 71             'del'=>$type
 72         );
 73         $msg = $type ? '删除' : '还原';
 74         $location = $type ? U('Admin/Blog/index','','') : U('Admin/Blog/recycle_bin','','');
 75         if(M('blog')->save($update)) {
 76             $this->success($msg.'成功' ,$location);
 77         } else {
 78             $this->error($msg.'失败');
 79         }
 80     }
 81     
 82     //回收站
 83     public function recycle_bin() {
 84         $this->blog = D('BlogRelation')->get_blogs(1);
 85         $this->display('index');
 86     }  
 87     
 88     //彻底删除
 89     public function delete() {
 90         $id = (int)$_GET['id'];
 91         //使用关联模型删除 或 手动删除
 92         if(D('BlogRelation')->relation('attr')->delete($id)) {
 93             $this->success('删除成功',U('Admin/Blog/recycle_bin'));
 94         } else {
 95             $this->error('删除失败');
 96         }        
 97     }
 98     
 99     //清空回收站
100 }

 

posted @ 2016-02-25 01:10  nemo20  阅读(5520)  评论(0编辑  收藏  举报
访客数:AmazingCounters.com
2016/05/17 起统计