Laravel 'User' model no id column

徘徊边缘 提交于 2019-12-11 06:22:52

问题


I'm getting an error when trying to Auth::attempt() with the User model saying that I do not have a 'id' column in my table. I am using the 'username' field as the primary key in my table and I didn't want to make an int 'id' column as the primary key. Is there anyway I can change the primary key column in the User model?

Error:

My user model:

    <?php

use Illuminate\Auth\UserTrait;
use Illuminate\Auth\UserInterface;
use Illuminate\Auth\Reminders\RemindableTrait;
use Illuminate\Auth\Reminders\RemindableInterface;

class User extends Eloquent implements UserInterface, RemindableInterface {

    use UserTrait, RemindableTrait;

    protected $table = 'users';

    protected $hidden = array('password', 'remember_token');


        public function getRememberToken()
        {
            return $this->remember_token;
        }   

        public function setRememberToken($remember_token) 
        {
            $this->remember_token   =   $remember_token;
        }

        public function getRememberTokenName()
        {
            return 'remember_token';
        }

        public function isAdmin()
        {
            return $this->isAdmin   ==  1;
        }

}

回答1:


To override the primary key used to search you must define the primaryKey property on the User model.

class User extends Eloquent implements UserInterface, RemindableInterface {

    use UserTrait, RemindableTrait;

    protected $primaryKey = 'username';
...

Now laravel will use the username column as the primary key column.

See the below quote from the laravel documentation.

Note: Eloquent will also assume that each table has a primary key column named id. You may define a primaryKey property to override this convention.

-- Eloquent - Basic Usage



来源:https://stackoverflow.com/questions/27763020/laravel-user-model-no-id-column

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!