Change default primary key in Eloquent

前端 未结 6 434
长发绾君心
长发绾君心 2020-12-05 01:58

Can I change Eloquent model primary key.

I want to set primary key for example admin_id instead of \'id\'?

I know I can change table name for m

相关标签:
6条回答
  • 2020-12-05 02:00

    To assign a primary key you should..->

    class User extends Eloquent {
    
        protected $primaryKey='admin_id';
    
     }
    
    0 讨论(0)
  • 2020-12-05 02:07

    The primary key variable is case sensitive and must be $primaryKey to work.

    Example:

    protected $primaryKey = 'your_primary_key_id';

    Example within a Model class:

    class User extends Eloquent {
    
        protected $primaryKey = 'your_primary_key_id';
    
    }
    
    0 讨论(0)
  • 2020-12-05 02:09

    If you are wanting to use a composite key (a string)

    You need to make sure you set public $incrementing = false otherwise laravel will cast the field to an Integer, giving 0

    class User extends Model {
    
        protected $primaryKey = 'my_string_key';
        public $incrementing = false;
    
    }
    
    0 讨论(0)
  • 2020-12-05 02:15

    Yes

    class User extends Eloquent {
    
        protected $primaryKey = 'admin_id';
    
    }
    
    0 讨论(0)
  • 2020-12-05 02:18
    class User extends Eloquent {
    
        protected $primaryKey = 'admin_id';
    
    }
    

    As per Laravel documentation :


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

    In addition, Eloquent assumes that the primary key is an incrementing integer value, which means that by default the primary key will be cast to an int automatically. If you wish to use a non-incrementing or a non-numeric primary key you must set the public $incrementing property on your model to false.

    0 讨论(0)
  • 2020-12-05 02:19
    class User extends Eloquent {
    
        protected $primarykey = 'admin_id';
    
    }
    

    but

    class User extends Eloquent {
    
        protected $primaryKey = 'admin_id';
    
    }
    

    note the letter K (capital) on the variable $primaryKey

    0 讨论(0)
提交回复
热议问题