在Laravel的默认UserController和用户模型中ORM不起作用

时间:2018-06-19 12:04:08

标签: laravel laravel-5 orm relationship

我想获得明智的用户角色。这是我面临的错误....

UserController.php(用户控制器文件)

namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Requests\UserRequest;
use App\Employee;
use App\Role;
use App\User;
use App\Site;
use App\Client;
use App\ProjectType;
use App\UserPermission;
use Auth;
use DB;
use App\Project;

class UsersController extends BaseController {

public function __construct() {
    $this->isSetClientAndProjectType();

    $data = User::with('Role')->first();        
    echo "<pre>";print_r(json_decode($data)); die;

    }
}

User.php(用户模型文件)

namespace App;
use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Database\Eloquent\SoftDeletes;

class User extends Authenticatable {

use SoftDeletes;

 use Notifiable;

protected $fillable = [
    'name', 'role_id', 'password', 'siteid', 'email', 'status', 'allowed_to_bypass_pm', 'allowed_to_bypass_admin'
];
protected $hidden = [
    'password', 'remember_token',
];

// Get users roles
public function Role() {
    return $this->hasMany('App\Role', 'role_id', 'id');
 }
}

错误是

enter image description here

我该如何解决此错误?

帮帮我。

谢谢。

3 个答案:

答案 0 :(得分:0)

如果用户有很多“角色”,则应为public function roles()

您已定义:

单个用户具有role_id

因此您需要:

如果用户只有一个角色,它将是:

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

与角色模型相反的是:

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

由于许多用户可以具有相同的角色。

希望这会有所帮助。

答案 1 :(得分:0)

您需要添加belongsTo关系

namespace App;
use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Database\Eloquent\SoftDeletes;

class User extends Authenticatable {

 use SoftDeletes, Notifiable;

 protected $fillable = [
    'name', 'role_id', 'password', 'siteid', 'email', 'status', 'allowed_to_bypass_pm', 'allowed_to_bypass_admin'
 ];

 protected $hidden = [
    'password', 'remember_token',
 ];

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

现在获取数据

$user = User::with('role')->find(1);
$role = $user->role;

答案 2 :(得分:0)

您需要确保您的表结构和外键引用与所使用的模型关系方法兼容。

例如,您在用户模型上使用了“ HasMany”关系。为此,您必须确保用户表(用户模型)中的每个记录/行在角色表(角色模型)中“具有许多”关联的记录/行。

在此,HasMany方法在角色表(角色模型)上假定外键“ role_id”。如果找不到,则会引发错误。

首先需要根据需要考虑角色和用户表的表结构(用户和角色模型),然后相应地添加模型关系方法。

如果您是第一次使用这些方法,可能会有些棘手,您可以参考laravel文档:

eloquent-relationships