laravel 有一个无法得到结果
laravel hasone not able to get the result
我正在尝试获取用户的角色,无论是管理员还是具有 hasOne 关系的客户端,但是当我尝试获取详细信息并执行 dd 时,我将 exists 设置为 false 任何人都可以帮助我吗
this is the result when im using dd in controller
//migration for user
public function up()
{
Schema::create('users', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->string('email')->unique();
$table->string('password');
$table->rememberToken();
$table->timestamps();
});
}
//角色迁移
public function up()
{
Schema::create('roles', function (Blueprint $table) {
$table->increments('id');
$table->unsignedInteger('user_id');
$table->enum('role',['Club Manager','Admin','Mc']);
$table->foreign('user_id')->references('id')->on('users');
$table->timestamps();
});
}
//用户模型
<?php
namespace App;
use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;
use \App\Role;
class User extends Authenticatable
{
use Notifiable;
/**
* The attributes that are mass assignable.
*
* @var array
*/
protected $fillable = [
'name', 'email', 'password',
];
/**
* The attributes that should be hidden for arrays.
*
* @var array
*/
protected $hidden = [
'password', 'remember_token',
];
public function Role(){
return null;
}
public function getrole(){
$role=$this->hasMany('App\Role');
return $role;
}
public function getuserRole(){
return Role::where('user_id',$this->id)->first();
}
}
//Controller
public function getrole(){
dd(Auth::user()->getrole());
}
您必须以 属性 而非方法的形式访问关系:
Auth::user()->getrole;
我正在尝试获取用户的角色,无论是管理员还是具有 hasOne 关系的客户端,但是当我尝试获取详细信息并执行 dd 时,我将 exists 设置为 false 任何人都可以帮助我吗
this is the result when im using dd in controller
//migration for user
public function up()
{
Schema::create('users', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->string('email')->unique();
$table->string('password');
$table->rememberToken();
$table->timestamps();
});
}
//角色迁移
public function up()
{
Schema::create('roles', function (Blueprint $table) {
$table->increments('id');
$table->unsignedInteger('user_id');
$table->enum('role',['Club Manager','Admin','Mc']);
$table->foreign('user_id')->references('id')->on('users');
$table->timestamps();
});
}
//用户模型
<?php
namespace App;
use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;
use \App\Role;
class User extends Authenticatable
{
use Notifiable;
/**
* The attributes that are mass assignable.
*
* @var array
*/
protected $fillable = [
'name', 'email', 'password',
];
/**
* The attributes that should be hidden for arrays.
*
* @var array
*/
protected $hidden = [
'password', 'remember_token',
];
public function Role(){
return null;
}
public function getrole(){
$role=$this->hasMany('App\Role');
return $role;
}
public function getuserRole(){
return Role::where('user_id',$this->id)->first();
}
}
//Controller
public function getrole(){
dd(Auth::user()->getrole());
}
您必须以 属性 而非方法的形式访问关系:
Auth::user()->getrole;