Pregunta

¿Puedo cambiar la clave primaria modelo elocuente?

¿Quiero establecer la clave primaria, por ejemplo, admin_id en lugar de 'ID'?

Sé que puedo cambiar el nombre de la tabla para el modelo como

protected $table = "admin";

¿Hay algo similar para la clave principal?

¿Fue útil?

Solución

si

class User extends Eloquent {

    protected $primaryKey = 'admin_id';

}

Otros consejos

class User extends Eloquent {

    protected $primarykey = 'admin_id';

}

pero

class User extends Eloquent {

    protected $primaryKey = 'admin_id';

}

Nota la letra K (Capital) en la variable $ PRAMARYKEY

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';

}
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.

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 $timestamp = false;

}

To assign a primary key you should..->

class User extends Eloquent {

    protected $primaryKey='admin_id';

 }
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top