https://github.com/Xethron/migrations-generator
我使用上述扩展程序,通过 php artisan migrate:generate
命令将我的数据库结构迁移到 Laravel 中。但是出现了一个小问题,我的主键并不是以 id 命名的,而是采用了一种不同的约定,为每个主键添加了前缀,例如 user_id、product_id、photo_id 等。当然,所有这些都是自动递增的。
以下是我的 migrations 文件夹中的 create_users_table.php 文件。我定义了 user_id 来覆盖默认的 id 选项,这样使用是否正确?
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
class CreateUsersTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('users', function (Blueprint $table) {
$table->primary('user_id');
$table->integer('user_id', true);
$table->string('name', 500);
$table->string('email', 500);
$table->string('password', 500);
}
);
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::drop('users');
}
}
我阅读了相关内容,发现需要添加以下内容,但我不确定该在哪里定义protected $primaryKey
,因为我的类继承的是Migration而不是Eloquent。
class CreateUsersTable extends Eloquent {
protected $primaryKey = 'user_id';
}
当我访问/auth/login页面时,出现以下错误,我认为这是由于使用user_id而不是id造成的。我该如何修复它?
SQLSTATE[42S22]: Column not found: 1054 Unknown column 'users.id' in 'where clause' (SQL: select * from `users` where `users`.`id` = 5 limit 1)
id
作为主键,你会发现生活更轻松,但是当你移植像你这样的应用程序时,有时打破这些约定是有意义的。在大多数情况下,Laravel 有办法适应这种情况。 - Ben Claar