当尝试使用外键获取类型时,Laravel关系返回null

时间:2017-01-20 11:14:38

标签: php laravel laravel-5 eloquent laravel-5.2

我正在尝试使用users表中的外键(即user_types_id)来获取用户类型,但是当我这样做时,我只得到null并且无法进入函数userTypeUser 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();
        });
    }

1 个答案:

答案 0 :(得分:3)

您已将您的关系命名为 userType ,因此 Eloquent 会假定外键名为 user_type_id ,而不是 user_types_id

替换

return $this->belongsTo(UserType::class);

return $this->belongsTo(UserType::class, 'user_types_id');

告诉 Eloquent 外键列的名称,它应该有效。