Я пытаюсь выбрать тип пользователя, используя внешний ключ в таблице пользователей, т.е. 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();
});
}
Вы назвали свое отношение UserType, следовательно красноречивый предполагает, что внешний ключ называется user_type_id, не user_types_id.
замещать
return $this->belongsTo(UserType::class);
с
return $this->belongsTo(UserType::class, 'user_types_id');
сказать красноречивый имя столбца внешнего ключа и оно должно работать.
Других решений пока нет …