当前位置:网站首页>Detailed explanation of ThinkPHP 5.0 Model Association

Detailed explanation of ThinkPHP 5.0 Model Association

2022-06-24 09:40:00 BigChen_ up

I believe many young friends are just beginning to learn thinkphp5.0 I can't understand the meaning of the parameters in the model association , Here is a detailed introduction :

One to one connection :hasOne(‘ Association model name ’,‘ Foreign key name ’,‘ Primary key name ’,[‘ Model alias definition ’],‘join type ’);

You can see a one-to-one relationship hasOne There are many parameters in , But the first three parameters are the most important .

The first parameter ‘ Association model name ’ ,tp5 This is what the manual says :‘ Every user has a profile ’.
To be more specific , You can use it in the user model hasOne Associated profile , So the first parameter is The model name of the profile . Look at the code :

namespace app\index\model;

use think\Model;

class User extends Model {
    

    public function profile() {
    
        return $this->hasOne('Profile');
    }
}

The second parameter is ‘ Foreign key name ’ In fact, that is You need to associate Profile The primary key name of the table .

The third parameter is the primary key name , Is what your current model is associated with Profile Corresponding to table PK Field name .

	public function profile() {
    
		//  The second parameter  id  yes  Profile  Tabular  id,  The third parameter  pid  It is required to follow the current model Profile The fields associated with the primary key of the table 
        return $this->hasOne('Profile','id','pid');
    }

To use, you need to instantiate the model first Then query the data with -> To get the desired data :

$user = User::get(1);
//  Output Profile Of the association model email attribute 
echo $user->profile->email;

One to many associative The parameters are almost the same as one-to-one , Learn one-to-one association and other associations can also do basic operations .

原网站

版权声明
本文为[BigChen_ up]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/175/202206240807401843.html