Home  >  Article  >  PHP Framework  >  How to use thinkphp association model

How to use thinkphp association model

尚
forward
2020-04-01 09:19:353137browse

How to use thinkphp association model

thinkphp comes with the associated model HAS_MANY.

Use, create ProductModel.class.php in the Model folder

The code is as follows:

<?php
namespace Test\Model;
<span style="color:#FF0000;">use Think\Model\RelationModel;</span>
 
	class ProductModel extends <span style="color:#FF0000;">RelationModel</span>{  
 
		protected $_link = array(
		
		&#39;attr&#39; =>array(
			&#39;mapping_type&#39; => self::HAS_MANY,
					&#39;class_name&#39; => &#39;attr&#39;,
					&#39;foreign_key&#39; => &#39;product_id&#39;,
					&#39;mapping_name&#39; => &#39;a&#39;,                //用来取数据
					&#39;mapping_fields&#39; => &#39;id,name,value&#39;,
					// &#39;as_fields&#39; => &#39;id,name,value&#39;,
					)
 
		);}

How to use it in the controller:

public function testRelation(){
 
        $postData = I(&#39;post.&#39;);
        // dump($postData);die;
 
        $productModel  = D("Test/Product");
 
        $data[&#39;name&#39;]   = $postData[&#39;phone_name&#39;];
          // $data[&#39;thumb&#39;]  = $photo[0];
        $data[&#39;thumb&#39;]  = &#39;kk&#39;;
        $data[&#39;create_time&#39;] = time();
       <span style="color:#FF0000;"> $data[&#39;a&#39;]= array(                     //这里为二维数组,因为是HAS_MANY模型
          array( &#39;name&#39;    => &#39;color&#39;,
          &#39;value&#39;   => serialize($postData[&#39;phone_color&#39;])),
          array(
            &#39;name&#39;    => &#39;size&#39;,
            &#39;value&#39;   => $postData[&#39;phone_size&#39;]),</span>
          
        );         
 
        $result = $productModel->relation(true)->add($data);  
        dump($result);exit;
    
  }

How to use thinkphp association model

How to use thinkphp association model

Recommended tutorial: thinkphp tutorial

The above is the detailed content of How to use thinkphp association model. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:csdn.net. If there is any infringement, please contact admin@php.cn delete