Thinkphp5.0 model hasOne, hasMany, belongsTo Detailed

ThinkPHP5 associated with an operating models, but some beginners on the data in the table are several common relational tables and tables, there are still problems, so use good relational query. 

Here hasOne, hasMany, belongsTo for a detailed illustration. 

First, it's roughly three Chinese meaning: 

hasOne: there is one, should be combined with the main predicate, A a B 
hasMany: There are many, A has many B 
belongsTo: belong, A belongs to B 


where we prepare three tables to understand their relationship: 
user_group user group table: the above mentioned id, title 
the user user list: the above mentioned id, user_group_id, username, password 
Profile user information table: the above mentioned id, user_id, the Nickname, Sex


 1 , the user table need to be associated user_group table, representing each user needs to know the user which user packets;
 2 , Profile table needs associated with the user table, indicating that the user information data which user information; 

we know a user group the following can have many users, so: user_group hasMany user; 
a user belongs to a user group, so: user belongsTo user_group; 

the same is user_group and user tables, but we have a different starting point, not the same relationship. 


Each user should have a unique user information data, so: user hasOne profile; 
a user information belongs to a user, so: profile belongsTo user

In summary: 

the User model, we can define the associated: 

function USER_GROUP () {
     return  $ the this -> a belongsTo ( 'the UserGroup' ); 
} 
 
function Profile () {
    return  $ the this -> the hasOne ( 'Profile <br>' ); 
} 
Us in the query: 

$ user = Model ( 'the User') -> Find ();
 $ user = $ user -> USER_GROUP; // this user in the current data can comprise data corresponding to the user_grou 
$ user = $ user -> profile; // this user in the current data can comprise data corresponding to the profile 


in UserGroup model, we can define the associated: 

function user () {
    return  $ the this-> the hasMany ( 'the User' ); 
} 
in the Profile model, we can define the associated: 

function User () {
     return  $ the this -> a belongsTo ( 'the User' ); 
} 


Note: The definition of the associated function name of the method can be arbitrarily defined, usually a table name or model name; we define a function, but understood to acquire property, so do not add () getting; 

a lot of people understand that I defines a method profile, so it should $ the User -> profile () here pay special attention to the next. 

So when we inquiries, convenient, without the use of a large number of join.

 

Guess you like

Origin www.cnblogs.com/kangshuai/p/12051718.html