【问题标题】:Laravel relationship returning null when tryying to fetch type using foreign key尝试使用外键获取类型时,Laravel 关系返回 null
【发布时间】:2017-01-21 21:41:03
【问题描述】:

我正在尝试使用用户表中的外键获取用户类型,即user_types_id,但是当我这样做时,我只得到null,并且无法进入User Model 中的函数userType。任何帮助将不胜感激。

提前谢谢你。我已经提供了相关的模型和表格

控制器

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);
        }
    }

用户类型模型

    <?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();
        });
    }

【问题讨论】:

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


    【解决方案1】:

    您已将关系命名为 userType,因此 Eloquent 假定外键称为 user_type_id,而不是 user_types_id强>。

    替换

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

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

    告诉 Eloquent 外键列的名称,它应该可以工作。

    【讨论】:

    • 它确实对我有用......非常感谢你的帮助...... :) 哦,好吧......我的错......
    • Eloquent 会对键名做出一些假设,如果您没有明确提供它们。它假定主键称为“id”,它还从关系名称派生外键。
    • 是的,我明白了……外键中不应该有那个“s”……这对我来说太愚蠢了,但是谢谢……:)
    猜你喜欢
    • 1970-01-01
    • 2020-07-12
    • 2021-01-22
    • 2014-08-21
    • 1970-01-01
    • 2021-07-08
    • 1970-01-01
    相关资源
    最近更新 更多