"thinkphp" Some ideas about thinkphp correlation model and view model

Source: Internet
Author: User

The view model is more like a table virtual table, and the view contains a series of column and row data with names. However, the view does not exist in the database as a stored set of data values. Row and column data is derived from the table referenced by the query that defines the view, and is generated dynamically when the view is referenced. The view acts like a filter for the underlying table referenced in it, which is what the thinkphp manual says.

In fact, the view model is the MySQL multi-table query only, the view model does not support multiple table updates, delete


The association model is a combination of results from multiple table queries, and it queries MySQL multiple times (after executing the main table query, there will be a _after_select) and then combining the result set. In some cases, the query of the correlation model is still quite good.

Here are some insights and comparisons of personal use of thinkphp model and view model

One: Performance aspects

View model, which is the correlation query, one query multiple tables

Correlation model, each query a table, multiple queries, and then combine the result set (INSERT, UPDATE, delete is the same.) )

Personally feel that the view model performance will be better (not all of them, not specifically tested)

Second: Query

If it is a query, it is strongly recommended to use the view model to do, simple, easy to understand and change, and the correlation model is too many definitions, and the result set of processing, debugging, is not as convenient as the view model.

Three: Insert, UPDATE, delete

View model does not support, association model support, but in the insertion, update, can not use the model of the Create method, as well as auto-completion, Automatic Updates are invalid, I myself rewrite a create, give you some hints, you can change as needed.

/**     *  overloads the Create method, does not filter the fields, and generates required data      */     function create ($data  =  ',  $type  =  ')  {         //  If no value is passed, the default is to take post data         if  ( Empty ($data))  {             $data  =  $_post;        } elseif  (Is_object ($data))  {              $data  = get_object_vars ($data);         }        //  Validating data         if  (Empty ($data)  | |  !is_array ($data))  {             $this- >error = l (' _data_type_invalid_ ');            return false;         }        //  Status           $type  =  $type  ?  $type  :  (!empty ($data [$this->getpk ()  ] )  ? self::model_update : self::model_insert);         //  Data automatic verification         if  (! $this->autovalidation ($data,   $type)  return false;        //  form token validation          if  (! $this->autochecktoken ($data))  {              $this->error = l (' _token_error_ ');             return false;         }        //  validation completed generating data Objects          if  ($this->autocheckfields)  { //  open field detection   filter illegal field data               $fields  =  $this->getdbfields ();             foreach  ($data  as  $key  =>  $val)  {                if   (magic_quotes_gpc && is_string ($val))  {                      $data [$key] =  Stripslashes ($val);                 }            }         }        //  create complete automatic processing of data          $data = $this->autooperation ($data,  $type);         $data = $this Createdata ($data);        //  returns the data created for other calls          return  $data;    }    /**      *  automatic Form processing      *  @access  public      *  @param  array  $data   Create data      *  @param  string  $type   Create types      *  @return  mixed      */    private function autooperation ($data,  $type)  {         if  (!empty ($this->options[' auto '))  {             $_auto =  $this->options[' auto '];             unset ($this->options[' auto ');         } elseif  (!empty ($this->_auto))  {             $_auto =  $this->_auto;        }         //  Auto-Fill         if   (Isset ($_auto))  {            foreach   ($_auto as  $auto)  {                 //  fill factor definition format                  // array (' field ', ' Fill content ', ' Fill condition ', ' additional rules ', [additional parameters])                  if  (Empty ($auto [2])   $auto [2] = self::model_insert;  //  Auto-Fill when new is added by default                  if  ($type  ==  $auto [2] | |   $auto [2] == self::model_both]  {                     switch  (Trim ($auto [3])  {                          case  ' function ': //   use functions to populate   field values as parameters                           case  ' callback ': //  using callback method                               $args  = isset ($auto [4])  ?  (array) $auto [4] :  array ();                             if  (Isset ($data [$auto [0]])   {                                 array_unshift ($args,  $data [$auto [0]]);                             }                              if  (' function '  ==  $auto [3])  {                                   $data [$auto [0]] = call_user_func_array ($auto [1],  $args);                              } else {                                   $data [$auto [0]] = call_user_func_array (Array ( & $this,                                       $auto [1]                                 )  ,  $args);                              }                              break;                         case  ' field ': //  is populated with values from other fields                                $data [$auto [0]] =  $data [$auto [1]];                              break;                         case  ' Ignore ': //  empty ignore                               if  (" ===  $data [$auto [0]])  unset ($data [$auto [0]]);                              break;                         case   ' String ':                         default: //  by default as a string fill                               $data [$auto [0]] =  $auto [1];                         }                         if   (false ===  $data [$auto [0]]  unset ($data [$auto [0]]);                     }             }        }         return  $data;    }         /**     *  generate the data required by the correlation model      */     fUnction createdata ($data)  {        foreach  ($data   as  $k  =>  $v)  {             if  (In_array ($k,  $this->fields)  {                  $data [' article '] [$k] =  $v;                 unset ($data [$k]);             }        }         //Delete Extra Fields         unset ($data [' nid '] );         unset ($data [' create_date ']);         return  $data;     }


is directly copied the original create method, but removed the field filter, and then automatically verify, automatic completion, the Createdata method to generate the final data, I think the official should modify this piece, it is better.

Other: Because I define the INSERT, UPDATE, delete, query, etc., are in the Commonaction public class, if there are special conditions to use the associated query, then if you use the associated view, also change to $model->relation (true)->select ( ) in a way that the individual feels is not very convenient, the direct view model does not need to be changed.

Debug: The View model prints all SQL statements for the associated query, and the associated model only prints the first SQL statement (because they are executing multiple SQL statements)


Welcome Dabigatran: 2,527,991,671 Learning Progress

This article is from the "Deanne Lei" blog, please be sure to keep this source http://a3147972.blog.51cto.com/2366547/1563416

"thinkphp" Some ideas about thinkphp correlation model and view model

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.