Transferred from: http://www.phpthink.cn/html/221.html
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, here is an area table for example descriptionthe concept of allowing defined propertiesClass Usermodel extends model{protected $_link = Array (' area ' =>array (' mapping_type ' = Belon gs_to, ' mapping_name ' = ' area ', ' class_name ' and ' area ', ' foreign_key ' + ' is A_id ',),);} In the above code, Mapping_type,foreign_key ... These, isallowed properties to be defined
------------------------- Overview of all definable properties --------------------------------
mapping_type The content defined by the Mapping_type that defines the association type of the table and the primary table must be constant, in total the following four ways:Has_one indicates that the current model (the primary table) has a sub-object, such as the user_info in this example, where each member corresponds to a tablebelongs_to indicates that the current model belongs to a different parent object, for example, each member belongs to a regionHas_many indicates that the current model has multiple child objects, such as multiple interest cards per userMany_to_many indicates that the current model can belong to more than one object, whereas a parent object may contain more than one child object, often requiring an intermediate table class constraint and association 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_keyThe associated foreign key name Foreign_key if not defined, the default isCurrent Data Object name +_id as foreign key For example: Usermodel the corresponding table is Think_user (note: Think is just a data table prefix, can be configured arbitrarily) then the foreign key of the Think_user table is user_id by default, if not, it is explicitly specified with this property, For example, if the foreign key defined by the data table is userId, then 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_keySelf-referencing associated word defaults think parent_id(belongs_to and Has_many only have this attribute) A self-referential association is a special association, that is, the association table is the current table.
Mapping_limitNumber of records associated to return(Has_many and Many_to_many only have this attribute)
Mapping_orderSort the associated query(Has_many and Many_to_many only have this attribute)
Relation_foreign_keyForeign key name of the associated table(Many_to_many Exclusive properties) 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 it is not, you can specify it by this property
relation_tableThe Associated intermediate table name(Many_to_many Exclusive properties) If this property is not set, by default the Getrelationtablename method of the current model is automatically obtained, for example, if the current model is user and the association model is group, then the name of the associated table will be formatted by default using User_group. The default intermediate table naming convention is: if there is a corresponding intermediate table for the two tables, the intermediate table is nameddata Table Prefix +_ + associated operation Main Table name +_+ Association table name For example, in this example, the table is manipulated by the Think_user table, so the intermediate table name for the Think_group table is Think_user_group, and if you are manipulating from the Think_group table, the middle name is Think_group_user, In other words, many-to-many associations must have a model class that explicitly defines 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 = Array ( Array (' ID ' =>1, ' card ' = ' 12345678 '),//Consumer card account 1 Array (' ID ' =>2, ' card ' = ' 88888888 '),//Consumer card account 2 ); //user's interest group data $User->group = Array ( Array (' ID ' =>1),//harp 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 update-------------------------------*/ $user [' id '] = $id; $user [' name '] = ' TP '; /has_one associated data updates are directly assigned $user [' UserInfo '] [' email '] = ' [email Protected] '; //note has_many The associated data to add the value of the primary key //Can update part of the 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);/*--------------Association Delete------------ -------------------*/ $User->relation (True)->delete ($id);/*---- ----------------------------------------------------*/ $this Assign (' Info2 ', ' User ID is '. $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 Association write Protected $autoReadRelations = true; //Auto correlation 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,The values defined by the Mapping_name property of other model classes are mapped to one of the properties of the user data object in the user data object, MO Mapping_name property is the associated model class name. If it is a one_to_one association, and the As_fields field mapping is defined, the field that is set by As_fields is directly the field of the User data object, in the same way that the single table model is used in the data processing mode, that is, the direct assignment is: $User- >email = ' [email protected] '; $User->nickname = ' fleeting '; the relation () method has been improved in the ThinkPHP1.6 version, simplifying some of the previously familiar Xfind (), Xfindall (), Relationget (), Relationadd (), Relationsave (), Relationdel () All of these methods are integrated into the newly defined relation (), directly supporting 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 it is Has_many's associated data, add the value of the primary key, you can update some data or add new data $user [' Card '] = array (' id ' = >1, ' card ' = ' 66666666 '),//update the primary key to 1 of the record 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.
Full definition of "associated operations" in the thinkphp framework