Laravel 5.1 : 迁移现有数据库
Laravel 5.1 : Migrate existing database
https://github.com/Xethron/migrations-generator
我在上述扩展的帮助下使用 php artisan migrate:generate
命令将我的数据库结构迁移到 Laravel。但是有一个小问题,我的主键没有命名为 id,我宁愿通过为每个主键添加前缀来使用不同的约定,例如 user_id、product_id、photo_id 等. 当然,所有这些都是自动递增的。
这是我的迁移文件夹中当前的 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
,因为我的 class 扩展了 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)
您需要在 User
模型中指定您的非默认主键:
namespace App;
use Illuminate\Database\Eloquent\Model;
class User extends Model {
protected $primaryKey = 'user_id';
您需要为所有不使用 id
作为主键的模型执行此操作。
https://github.com/Xethron/migrations-generator
我在上述扩展的帮助下使用 php artisan migrate:generate
命令将我的数据库结构迁移到 Laravel。但是有一个小问题,我的主键没有命名为 id,我宁愿通过为每个主键添加前缀来使用不同的约定,例如 user_id、product_id、photo_id 等. 当然,所有这些都是自动递增的。
这是我的迁移文件夹中当前的 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
,因为我的 class 扩展了 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)
您需要在 User
模型中指定您的非默认主键:
namespace App;
use Illuminate\Database\Eloquent\Model;
class User extends Model {
protected $primaryKey = 'user_id';
您需要为所有不使用 id
作为主键的模型执行此操作。