我有3个型号:
用户,角色和分支。
它们之间的关系是这样的:
倾倒用户模型:
class User extends Model
{
// Define fields to be fillable
protected $fillable = [
'firstname',
'lastname',
'telephone',
'address',
'password',
'code',
'status',
'branches_id',
'roles_id'
];
/**
* Get the role record associated with the user.
*/
public function role()
{
return $this->hasOne('App\Role');
}
/**
* Get the branch record associated with the user.
*/
public function branch()
{
return $this->hasOne('App\Branch');
}
}
对于榜样:
class Role extends Model
{
// Define fields to be fillable
protected $fillable = ['description'];
/**
* Get the user that owns the role.
*/
public function user()
{
return $this->belongsToMany('App\User');
}
}
对于分支模型:
class Branch extends Model
{
// Define fields to be fillable
protected $fillable = ['description', 'location'];
/**
* Get the user that owns the branch.
*/
public function user()
{
return $this->belongsToMany('App\User');
}
}
我知道,如果我使用Blade来列出用户的角色,我可能会完成以下操作:$ user-> role()
但是我试图在前端使用angular 2,在后端使用laravel 5.3。
我的问题是如何与角色和分支一起检索用户
这是我的UserController中的索引操作:
public function index()
{
// Get all users, along with roles and branches
$users = User::all();
// Send the response
return response()->json([
'users' => $users
], 200);
}
使用急切加载:
$users = User::with('role', 'branch')->get();
另外,如果用户具有一个角色和一个分支,则关系应belongsTo()
改为belongsToMany()
:
return $this->belongsTo('App\User');
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句