The association orm model laravel

1, one to one relationship

$ this-> hasOne ( association model , [ association model link key ] , [ the present model the link key ]);

return $this->hasOne(Extuser::class, 'uid', 'id');

Association table name of the foreign key user_id    this table primary key ID is id

return $this->hasOne(Extuser::class);

Write one relationship

// user master table from the table to one user model Method 
public userExt function () {
return $ this-> the hasOne (UserExt :: class);
}
// used in the controller
$user = User::with('userExt')->find(1);
dump($user->toArray());

2, many relationships
in the actual project in a user published a number of articles, the relationship between such a relationship is one to many.

$ this-> hasMany ( association model , [ association model link key ] , [ the present model the link key ]);

return $this->hasMany(App\Phone::class, 'foreign_key', 'local_key');

// many model 
public Articles function () {
return $ this-> the hasMany (Article This article was :: class, 'UID');
}
// controller
:: with the User Data = $ ( 'Articles') -> Find (. 1); 
the dump ($ DATA-> toArray ());

. 3, many relationship

$ this-> belongsToMany ( association table model , the intermediate table table , the intermediate table of this model the correlation ID , the intermediate table associated model of off associated ID);

return $this->belongsToMany(App\User::class, 'user_auth_table', 'user_id', 'auth_id');

// 多对多 模型
public function auths(){
return $this->belongsToMany(Auth::class,'user_auth','user_id','auth_id');
}
$user = User::find(1);
$data = $user->auths();
dump($data->get()->toArray());

 



 


Guess you like

Origin www.cnblogs.com/konglingxin/p/11302165.html