Laravel:用户和角色关系(用户只有一个角色)

时间:2018-11-15 09:15:24

标签: php laravel

因此,我在Users table上为用户角色添加了一个列,即role; 用户只能有一个角色,角色返回 null

Role.php(模型)

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Role extends Model
{
    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'role'
    ];

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

User.php(模型)

<?php

namespace App;

use Illuminate\Notifications\Notifiable;
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Database\Eloquent\Model;

class User extends Authenticatable
{
    use Notifiable;
    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'first_name', 'last_name', 'role', 'first_login', 'last_login', 'email', 'password',
    ];

    /**
     * The attributes that should be hidden for arrays.
     *
     * @var array
     */
    protected $hidden = [
        'password', 'remember_token',
    ];

    public function role() {
        return $this->belongsTo('App\Role');
    }
}

UserController.php(仅索引)

public function index()
{
    $users = User::with('role')->get();

    return view('users.index')->with('users', $users);
}

index.blade.php

@extends('layouts.app')

@section('content')
<div class="container">
    <h1>USERS</h1>
    <div class="table-responsive">
        <table class="table">
            <thead>
                <tr>
                    <th>Name</th>
                    <th>Email</th>
                    <th>Role</th>
                </tr>
            </thead>
            <tbody>
                @foreach($users as $user)
                <tr>
                    <td>{{$user->first_name}} {{$user->last_name}}</td>
                    <td>{{$user->email}}</td>
                    <td>{{$user->role}}</td>
                </tr>
                @endforeach
            </tbody>
        </table>
    </div>

</div>
@endsection

用户角色为。 怎么做呢?

表结构

+-------+
| Users |
+-------+
| id    |
| role  | -> id of role
| ...   |
+-------+


+-------+
| Roles |
+-------+
| id    |
| role  | -> name of role
| ...   |
+-------+

2 个答案:

答案 0 :(得分:3)

默认情况下,它将在用户表中搜索role_id列,如果不是这样,则需要指定相关列。将您的关系更改为以下内容:

public function role() {
    return $this->belongsTo('App\Role', 'role');
}

答案 1 :(得分:0)

尝试这个

public function role() {
    return $this->belongsTo('App\Role', 'role');
}
  

属于功能文档

$this->belongsTo(modelName,foregin key,local key)
  

用于hasMany函数

$this->hasyMany(modelName,foregin key,local key)