thinkphp关联模型

2015-07-24 10:47:38 · 作者: · 浏览: 3


thinkphp 自带关联模型HAS_MANY。

使用,在Model文件夹下创建ProductModel.class.php

代码如下:

use Think\Model\RelationModel;

	class ProductModel extends RelationModel{  

		protected $_link = array(
		
		'attr' =>array(
			'mapping_type' => self::HAS_MANY,
					'class_name' => 'attr',
					'foreign_key' => 'product_id',
					'mapping_name' => 'a',                //用来取数据
					'mapping_fields' => 'id,name,value',
					// 'as_fields' => 'id,name,value',
					)
 
		);}

在控制器里的使用方法:

public function testRelation(){

        $postData = I('post.');
        // dump($postData);die;

        $productModel  = D("Test/Product");

        $data['name']   = $postData['phone_name'];
          // $data['thumb']  = $photo[0];
        $data['thumb']  = 'kk';
        $data['create_time'] = time();
        $data['a']= array(                     //这里为二维数组,因为是HAS_MANY模型
          array( 'name'    => 'color',
          'value'   => serialize($postData['phone_color'])),
          array(
            'name'    => 'size',
            'value'   => $postData['phone_size']),
          
        );         

        $result = $productModel->relation(true)->add($data);  
        dump($result);exit;
    
  }

\