理想情况下,您的表应命名users(以 s 结尾)roles和role_user,其中应包含user_idand role_id。
从那时起,配置模型就非常简单了:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class User extends Model
{
/**
* The roles that belong to the user.
*/
public function roles()
{
return $this->belongsToMany('App\Role');
}
}
角色:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Role extends Model
{
/**
* The users that belong to the role.
*/
public function users()
{
return $this->belongsToMany('App\User');
}
}
版:
显示用户及其角色的快速示例:
控制器
public function index()
{
$users = User::all();
return view('users.list', compact('users'));
}
假设模型中的关系定义明确,您只需执行以下操作:
文档对此进行了详细说明:https ://laravel.com/docs/5.3/eloquent-relationships#many-to-many
理想情况下,您的表应命名
users
(以 s 结尾)roles
和role_user
,其中应包含user_id
androle_id
。从那时起,配置模型就非常简单了:
角色:
版:
显示用户及其角色的快速示例:
控制器
看法
显然,属性名称发生了变化。我建议你阅读 Laravel 中的关系是如何工作的:https ://laravel.com/docs/5.3/eloquent-relationships