我正在尝试使用users表中的外键(即user_types_id
)来获取用户类型,但是当我这样做时,我只得到null
并且无法进入函数userType
在User Model
。任何帮助将不胜感激。
提前谢谢你。我提供了相关的模型和表格
控制器
public function dashboard() {
$userType = UserType::all();
$id = Auth::user()->id;
var_dump($id); // returns id
$users = User::find($id);
var_dump($user->user_types_id); // returns user_type_id in users table
if($users->userType){
var_dump($users->userType->types); // error is in here. Not taking userType.
} else {
echo 'does not exit';
}
die();
return view('dashboard', compact('users'));
}
用户模型
<?php
namespace App;
use Illuminate\Foundation\Auth\User as Authenticatable;
use App\UserType;
class User extends Authenticatable
{
/**
* The attributes that are mass assignable.
*
* @var array
*/
protected $fillable = [
'username', 'password',
];
/**
* The attributes that should be hidden for arrays.
*
* @var array
*/
protected $hidden = [
'password', 'remember_token',
];
public function userType() {
return $this->belongsTo(UserType::class);
}
}
UserType模型
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
use App\User;
class UserType extends Model
{
protected $fillable=['types'];
public function users() {
return $this->hasMany(User::class);
}
}
用户表
public function up()
{
Schema::create('users', function (Blueprint $table) {
$table->increments('id');
$table->integer('user_types_id')->unsigned()->index();
$table->string('username')->unique();
$table->string('password');
$table->string('salt');
$table->rememberToken();
$table->timestamps();
});
}
用户类型表
public function up()
{
Schema::create('user_types', function (Blueprint $table) {
$table->increments('id');
$table->string('types');
$table->timestamps();
});
}
答案 0 :(得分:3)
您已将您的关系命名为 userType ,因此 Eloquent 会假定外键名为 user_type_id ,而不是 user_types_id 强>
替换
return $this->belongsTo(UserType::class);
与
return $this->belongsTo(UserType::class, 'user_types_id');
告诉 Eloquent 外键列的名称,它应该有效。