簡體   English   中英

Auth :: user()關系返回null laravel 5.3

[英]Auth::user() relationship return null laravel 5.3

我的App\\User模型中有以下代碼。

class User extends Authenticatable
{
    use Notifiable;

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'username','dob','name', 'email', 'password',
    ];

    /**
     * The attributes that should be hidden for arrays.
     *
     * @var array
     */
    protected $hidden = [
        'password', 'remember_token','created_at','updated_at',
    ];

    protected $dates =[
        'dob',
    ];

    public function roleuser(){
        return $this->belongsTo('App\Role');
    }
}

CreateRolesTable類擴展了Migration {

public function up()
{
    Schema::create('roles', function (Blueprint $table) {
        $table->increments('id');
        $table->string('rolename');
        $table->timestamps();
    });
}


public function down()
{
    Schema::dropIfExists('roles');
}

}

類CreateUsersTable擴展了遷移{

public function up()
{
    Schema::create('users', function (Blueprint $table) {
        $table->increments('id');
        $table->integer('role_id')->unsigned()->default(2);
        $table->string('username',32);
        $table->date('dob');
        $table->string('name');
        $table->string('email');
        $table->string('password');
        $table->rememberToken();
        $table->timestamps();
    });
}


public function down()
{
    Schema::dropIfExists('users');
}

}

我正在使用用戶和角色之間的一對一關系。

從Blade模板調用{{ Auth::user()->roleuser }}返回null,但是我期望有一個App\\Role實例。

有人可以告訴我怎么了嗎?

我正在使用用戶和角色之間的一對一關系。

如果您使用的是一對一關系,則應使用hasOne方法 ,該方法將返回模型的實例,而不是像您想的那樣返回的集合(我認為這是您現在所獲得的(不是null))。

您必須定義用於關系的密鑰。 您沒有將任何其他參數傳遞給關系方法以覆蓋命名約定。 默認情況下,它會查找非常特殊的命名字段。 它會查找roleusers_id因為您將方法命名為roleusers而不是更普通的role名稱。 如果您將其命名為role則默認情況下會查找role_id字段。 如果將其保留為roleusers則需要覆蓋所使用的密鑰。 [文檔直接提到了這一點]

Laravel 5.3文檔-雄辯-關系-一對多(反向)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM