【发布时间】:2018-07-23 09:36:50
【问题描述】:
问题是:我正在尝试为我的表Users 生成一个非常简单的自定义primary key(通过覆盖函数getKey())。当我迁移表时,它说:
SQLSTATE[42000]: Syntax Error or Acccess Violation: 1072 Key Column 'uid' Doesn't Exist in Table (SQL: Alter Table 'users' Add Primary Key 'users_uid_primary'('uid'))
提前感谢您的建议和更正。
编辑:迁移后,我的表在 MySQL 中创建,但没有主键列(在本例中为“uid”)。
架构:
public function up()
{
Schema::create('users', function (Blueprint $table) {
$table->primary('uid');
$table->string('username');
$table->string('password');
$table->timestamps();
});
}
型号:
class User extends Model
{
protected $primaryKey = 'uid'; //emphasize that the primary key isn't 'id'
protected $keyType = 'string'; //p.k. holds string values
public $incrementing = false; //then p.k. must not auto increment it
public $timestamps = false; //no need for this one
public function getKey() {
return "u".rand(1000, 9999)."r"; //return something like 'u2548r'
}
}
【问题讨论】:
标签: laravel model eloquent artisan-migrate