加入Auth :: User Laravel 4的其他表

时间:2015-09-01 04:35:42

标签: php laravel

我有用户和用户组表。

在用户表中,它包含:id,name,email,usergroup_id [fk]

在usergroup表中,它包含:id [pk],usergroup

对于名字,我可以这样:

{{Auth::User()->name}}

usergroup.usergroup怎么样?

2 个答案:

答案 0 :(得分:0)

您可以为此创建关系one to many

user.php的

public function userGroup(){
 $this->belongsTo('Usergroup');
}

Usergroup.php

public function users(){
 $this->hasMany('User');
}

现在你可以通过以下方式获得:

Auth::user()->userGroup->usergroup;

它可能有效:)

答案 1 :(得分:0)

用户模型:

// here we saying that User belongs to a User group 
public function userGroup(){
     return $this->belongsTo(UserGroup::class,'usergroup_id');
}

UserGroup Model:

// here we saying that User group has many users 
public function user(){
    return $this->hasMany(User::class,'usergroup_id','id');
}

从用户对象中可以执行以下操作:

$userGroupObj = Auth::user()->userGroup();
// this would be a userGroup Object
// so now to get usergroup you can do
$userGroup = $userGroupObj->usergroup;

// Please make sure you check if($userGroupObj) before doing $userGroup = $userGroupObj->usergroup;

// So I would do something like
$userGroup = null;
$userGroupObj = Auth::user()->userGroup();
if($userGroupObj){
    $userGroup = $userGroupObj->usergroup;  
}

您可以从UserGroupObject执行以下操作:

$userObjCollection = $userGroupObject->user();
// this would be a user collection giving you all users in that group.