Full definition of "associated operations" in the thinkphp framework

Source: Internet
Author: User
Tags table definition

In complex association operations, if you want to add optional attributes to the association definition, we can take a fully defined approach. The fully defined format is: protected $_link = Array (' Associative table name 1 ' = = Array (' The table is associated with the property 1 ' = ' = ' = ' = ' = ' = ' = ', ' The table is associated with the property n ' = ') Define ', '), ' Association table name 2 ' = = Array (' The table is associated with a property of 1 ' = ' = ' = ', ' The table is associated with the property n ' = ' = ' = ') ', ' = ' = '); In the above format description, we used a modifier for the property: The way the table is associatedProperty. The definition of the associated operation is complicated and error prone, perhaps because of the more definable attributes, and because of the different associations, there are some differences in the definable attributes, in fact, as long as the understanding of this knowledge point, you will find the correlation operation is actually very simple. Let's take another way to chew on this most troublesome difficulty, first to understand all the attributes that allow the definition to be defined, and then to take a different kind of correlation. The complete way of definition, replacing the above format, would be similar to this, with an area table to illustrate the concept of allowing the definition of the attribute class Usermodel extends model{protected $_link = Array (' area ' =& Gt;array (' mapping_type ' = belongs_to, ' mapping_name ' = ' area ', ' class_name ' =&G T ' Area ', ' foreign_key ' = ' area_id ',),);} In the above code, Mapping_type,foreign_key ... These are the properties that are allowed to be defined


-------------------------an overview of all the properties that can be defined--------------------------------
Mapping_typeTo define the association type of the table to the primary table, the content defined by Mapping_type must be constant, in the following four ways: Has_one means that the current model (the primary table) has a child object, such as the user_info in this example, and each member corresponds to a table belongs_to Indicates that the current model belongs to a different parent object, for example, each member belongs to a region Has_many indicates that the current model has multiple child objects, such as multiple interest cards per user Many_to_many indicates that the current model can belong to more than one object, and the parent object may contain multiple child objects. Typically, an intermediate table class constraint and association is required between the two. For example, each member in this example can belong to more than one interest group, and each interest group can have more than one user class_nameThe name of the model class to associate. For example, the area defined by the sample code again reminds you to make sure that the Model class (Areamodel) is defined. Mapping_nameThe associated mapping name, used to get data, as a data index that is tied to the main table field in the data set. The name cannot be duplicated with the field of the current model, otherwise the conflicting mapping_name of the associated data acquisition is not defined, and the definition of class_name is taken as mapping_name. That is, the model class name Foreign_keyAssociated FOREIGN key name Foreign_key if not defined, the default is the current data object name +_id as a foreign key for example: Usermodel the corresponding table is Think_user (note: Think is just a data table prefix that can be configured arbitrarily) then THINK_ The foreign key of the user table defaults to user_id, and if not, it is explicitly specified with this property, such as the data table definition of the foreign key is userId, use ' foreign_key ' = ' userid ', this way to declare ConditionAssociation conditions, when the query is associated with the value of the foreign key automatically, if there are additional query conditions, you can use this property to define Mapping_fieldsThe association data for the default associated query is the entire field of the associated table if there is no definition for the field to query. If you only need to query the individual fields, you can use this property to specify As_fieldsMapping associated field values directly to a field in a data object This feature is unique to One_to_one (including Has_one and belongs_to) associations, and can be mapped directly to data objects rather than as an associative data. For example, when the field name of the associated data conflicts with the field names of the current data object, it can be defined in the following way: ' as_fields ' = ' email,nickname:username ', when the property is not defined, the data is similar to: ["id"] = String (1) "2" ["Name"] + string (8) "thinkphp" ["card"] = = Array (1) {[0] + array (1) {["card"] = = St Ring (8) "88888888"} if a mapping is defined, it is similar to ["id"] + = string (1) "2" ["Name"] + string (8) "thinkphp" ["Card"] and string (8) "88888888" Parent_keyThe associated word defaults of the self-referential association thinks PARENT_ID (BELONGS_TO and Has_many have this property) the self-referential association is a special association, that is, the association table is the current table. Mapping_limitThe number of records to be returned by the association (Has_many and Many_to_many have this attribute) Mapping_orderThe sort of the associated query (Has_many and Many_to_many only have this property) Relation_foreign_keyThe foreign key name of the associated table (Many_to_many exclusive property) The foreign key name of the default association table is the table name +_id for example, Relation_foreign_key in this example is group_id if not compliant, this property can be specified relation_tableThe Associated intermediate table name (Many_to_many exclusive property) If this property is not set, the default is automatically obtained through the Getrelationtablename method of the current model, for example, the current model is user, the association model is group, Then the name of the associated table is used by default in the format User_group. The default intermediate table naming convention is: if there is a corresponding intermediate table for the two tables, the intermediate table is named for the data table prefix +_ + The primary table name of the associated operation +_+ the associated table name, for example, in this example, by the Think_user table operation, so and THINK_ The middle table name of the group table is Think_user_group, if it is from the Think_group table, then the middle name is Think_group_user, that is, the many-to-many association settings, must have a model class inside need to explicitly define the intermediate table , otherwise the bidirectional operation will be faulted. In addition, there is no need to have an ID primary key for the field in the intermediate table (but even if this field is not affected by the intermediate table operation) The intermediate table is usually composed of user_id and group_id. If the intermediate table does not conform to the above rule, you need to explicitly specify the intermediate table name through this property. Various association types available properties are summarized below, which can be explained in terms of this table and reference Has_one Available PropertiesMapping_typeclass_namemapping_nameforeign_keyconditionmapping_fieldsas_fields belongs_to Available PropertiesMapping_nameforeign_keymapping_fieldsconditionparent_keyas_fields Has_many Available PropertiesMapping_nameforeign_keyparent_keymapping_fieldsmapping_limitmapping_order Many_to_many Available PropertiesOnce the Mapping_nameforeign_keyelation_foreign_keymapping_limitmapping_orderrelation_table association is defined, we can easily use the correlation action. The following sample code comes from an example of an associated operation of the official chief engineer, where all the code is posted before the focus is explained.  <?phpclass Indexaction extends action{    public function index () {         $User = D ("User");/*--------------Associated write-------------------------------*/        //Add user Data          $User->name =   ' thinkphp ';         $User->area_id   =  1;//East          //user profile data          $User->userinfo =  array (             ' email '   => ' [email protected] ',          ' nickname ' + ' fleeting ',         ';        //user's consumer card data          $User->card  &nbSp;=  array (            array (' id ' =>1, ' card ' = ' 12345678 '), Consumer Card Account 1            array (' id ' =>2, ' card ' = ' 88888888 '),//Consumer card account number 2            );        //User's interest group data          $User->group =  array (            array (' id ') =&GT;1),//piano             array (' id ' =>2),//chess          );        //Association Add user Data          $id = $User Relation (True)->add ();        //If the user data is not a users model but a data array         //can use         //$id = $User->relation (True)->add ($Data);          $this->assign (' info1 ', ' User Data association write complete! ‘);/*--------------related Queries-------------------------------*/         $user    =    $User->relation (True)->find ($id);         $this->assign (' User1 ', $ User);         $user    =   $User->relation (' UserInfo ') Find ($id);         $this->assign (' User2 ', $user);          $list    =   $User->relation (True)->findall ();          $this->assign (' list ', $list);/*--------------Associated updates  -------------------------------*/          $user [' id ']   = $id;         $user [' name '] = ' TP ';         //has_one associated data Direct assignment          $user [' UserInfo '] [ ' Email '] =   ' [email protected] ';        //Note that the associated data for Has_many is added to the mainThe value of the key         //can update some data          $user [' Card '] = Array (             array (' id ' =>1, ' card ' = ' 66666666 '),//update record for primary key 1             array (' card ' = ' 77777777 '),//Add a new record          );        //many_to_many Data Update is re-write          $user [' Group '] =  array (            array (' id ' =>2),        );         $User->where (' id= '. $id)->relation ( true)->save ($user);        //query for updated data          $user    =   $User->relation (True)->find ($id);         $this Assign (' User3 ', $user);/*--------------Associated Delete-------------------------------*/         $User->relation (True)->delete ($id);/*---------------------------------------------------- ----*/         $this->assign (' Info2 ', ' User ID '. $id. ' The data has been associated deleted! ');         $this->assign (' id ', $id);         $this- >display ();   }}?> Code Annotations: The TP correlation operation supports manual correlation and auto-correlation, and we see that the code above uses a manual association, which is controlled by the relation () method in the coherent operation, and can be set in Usermodel if an automatic association operation is required.  class Usermodel extends relationmodel{    protected $autoSaveRelations = true;         //Auto-Associate Save     protected $autoDelRelations   = true;         //Auto-Correlation Delete     protected $autoAddRelations   = true;        // Auto-correlate write     protected $autoReadRelations = true;        //auto-correlate query     Protected $_link = Array (...);} For example, when the auto-correlation query property is set to True, using $user->select (), the system automatically queries all the defined associated data, and the auto-associated application can perform its own test experience, and the official recommendation is that when multiple associations are defined for the model, Try to avoid the use of auto-correlation operations, so as not to affect performance. Then look at the code above, we use this method when inserting data://user profile Data $user->userinfo =  array (    ' email '   => ' [ Email protected] ',    ' nickname ' = ' fleeting ', because we define other model classes with the user model as the core, and other model classes Mapping_ The value defined by the Name property is mapped to one of the properties of the user data object in the user data object, MO The Mapping_name property is the associated model class name. Ifis a one_to_one association, and the As_fields field mapping is defined, the field that is set by the As_fields is directly the field of the User data object, which is the same as the single table model in the case of data processing, that is, the direct assignment can be: $User- >email    = ' [email protected] '; $User->nickname = ' fleeting '; relation () The method has been improved in version ThinkPHP1.6, simplifying the previous several familiar Xfind (), Xfindall (), Relationget (), Relationadd (), Relationsave (), Relationdel ( These methods, all integrated into the newly defined relation (), directly support the use of parameters for coherent operation. When we need to do correlation processing, we use relation (ture) this way: $id = $User->relation (True)->add (), if you want to specify the associated data, as in 34 lines of code, The parameters are passed in the relation method: $user = $User->relation (' UserInfo ')->find ($id), as for the associated update, it is important to note that the update of the Has_one associated data is directly assigned, $user the [' UserInfo ' [' email '] =   ' [email protected] '; If the associated data of the Has_many is the value of the primary key, you can update some data or add new data $user[' Card ' = Array (    array (' ID ' =>1, ' card ' = ' 66666666 '),//update record for primary key 1     Array (' card ' = ' 77777777 ') ,//Add a new record); Many_to_many The associated data is automatically deleted and processed when the association is inserted and updated.

When you open the log log for runtime/logs/or turn on debug mode, you can look at the generated SQL.

If you want to reprint the article, please specify: Reproduced from Phpthink this article link address: http://www.phpthink.cn/html/221.html

Full definition of "associated operations" in the thinkphp framework

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.