请注意:我对laravel和一般编程很陌生。
所以我在'user'和'role'之间有很多对很多的关系,并使用这个新东西,我刚刚学习了数据透视表'role_user'。现在,我想显示一个用户列表以及他们所拥有的角色的名称。
用户迁移
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreateUsersTable extends Migration
{
public function up()
{
Schema::create('users', function (Blueprint $table) {
$table->bigIncrements('id');
$table->string('name');
$table->string('email')->unique();
$table->timestamp('email_verified_at')->nullable();
$table->string('password');
$table->rememberToken();
$table->timestamps();
});
}
public function down()
{
Schema::dropIfExists('users');
}
}
角色迁移
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreateRolesTable extends Migration
{
public function up()
{
Schema::create('roles', function (Blueprint $table) {
$table->bigIncrements('id');
$table->string('name');
});
}
public function down()
{
Schema::dropIfExists('roles');
}
}
角色用户迁移
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreateRoleUserTable extends Migration
{
public function up()
{
Schema::create('role_user', function (Blueprint $table) {
$table->bigInteger('role_id')->unsigned();
$table->bigInteger('user_id')->unsigned();
});
}
public function down()
{
Schema::dropIfExists('role_user');
}
}
用户模型
namespace App;
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
class User extends Authenticatable
{
use Notifiable;
protected $fillable = [
'name', 'email', 'password', 'roles_id'
];
protected $hidden = [
'password', 'remember_token',
];
protected $casts = [
'email_verified_at' => 'datetime',
];
public function roles()
{
return $this->belongsToMany('App\Role');
}
public function authorizeRoles($roles)
{
if (is_array($roles)) {
return $this->hasAnyRole($roles) ||
abort(401, 'This action is unauthorized.');
}
return $this->hasRole($roles) ||
abort(401, 'This action is unauthorized.');
}
/**
* Check multiple roles
* @param array $roles
*/
public function hasAnyRole($roles)
{
return null !== $this->roles()->whereIn(‘name’, $roles)->first();
}
/**
* Check one role
* @param string $role
*/
public function hasRole($role)
{
return null !== $this->roles()->where(‘name’, $role)->first();
}
}
角色模型
namespace App;
use Illuminate\Database\Eloquent\Model;
class Role extends Model
{
public $timestamps = false;
public function users()
{
return $this->belongsToMany('App\User');
}
}
我的观点
@extends('layouts/app')
@section('content')
<div class="row">
<div class="col-md-12">
<div class="card">
<div class="card-header">
<h4>Users</h4>
</div>
<div class="panel-body">
@if (count($users) > 0)
<table class="table">
<thead>
<tr>
<th>Name</th>
<th>Email</th>
<th>Created on</th>
<th>Role</th>
</tr>
</thead>
@foreach ($users as $user)
<tr>
<td><em>{{$user->name}}</em></td>
<td><em>{{$user->email }} </em></td>
<td><em>{{$user->created_at}}</em></td>
<td><em>{{$user->roles->name}} </em></td>
<td>
<span class="table-remove">
{!!Form::open(['action' =>['userController@destroy', $user->id], 'method' => 'POST'])!!}
{{Form::hidden('_method', 'DELETE')}}
{{ Form::button('<i class="fas fa-trash-alt" aria-hidden="true"></i>', ['class' => 'btn btn-danger btn-sm', 'type' => 'submit']) }}
{!!Form::close()!!}
</span>
</td>
</tr>
@endforeach
</table>
</div>
</div>
</div>
</div>
@else
<p>No users found</p>
@endif
UserController
class UserController extends Controller
{
public function index()
{
$users = User::all();
return view('users.index',['users'=> $users]);
}
}
现在我得到了错误:
属性[名称]在此集合实例上不存在。 (查看:C:\ xampp \ htdocs \ Laravel \ AmbitieProject \ resources \ views \ users \ index.blade.php)
我尝试回显“ $ user-> roles-> name”,我认为它应该在一对多关系中起作用,但是我不确定如何使用多对多关系来回显角色的名称>
答案 0 :(得分:1)
您在定义关系时犯了一个错误。
请在关系中定义pivot
表。
角色模型
public function users()
{
return $this->belongsToMany('App\User', 'role_users'); //plural name
}
答案 1 :(得分:0)
您的数据透视表将返回Laravel Collection。因此,您必须先获取记录,才能访问记录的属性。
如果有许多可能的角色(自从您使用数据透视表路由以来,我认为这是对的),则应执行类似的操作将其列出为逗号分隔的列表:
<td>
<em>
@if ($user->roles->count() > 0)
{{ $user->roles->implode('name', ',') }}
@endif
</em>
</td>
如果只有一个角色,那么只需使用first()
即可获得第一条记录:
<td>
<em>
@if ($user->roles->count() > 0)
{{$user->roles->first()->name}}
@endif
</em>
</td>