【问题标题】:Laravel migration where id column not named "id" causes errorLaravel 迁移,其中 id 列未命名为“id”导致错误
【发布时间】:2021-12-19 02:49:04
【问题描述】:

如何创建与“id”不同的 id/主键列?当我尝试它时,它会产生一个错误。

class CreateEmployeesTable extends Migration
{
// ...
    public function up()
    {
        Schema::create('employees', function (Blueprint $table) {
            $table->id('employee_id');
            $table->string('first_name', 100);
            $table->string('last_name', 100);
            $table->string('email', 200);
            $table->timestamps();
        });
    }
// ...
}

试一试:

php artisan tinker
Psy Shell v0.10.8 (PHP 7.3.20 — cli) by Justin Hileman
>>> $employee = new App\Models\Employee
=> App\Models\Employee {#3452}
// ...
>>> $employee->save();
<warning>PHP Warning:  oci_execute(): ORA-00904: "ID": invalid identifier in <path>Statement.php on line 159</warning>
Yajra\Pdo\Oci8\Exceptions\Oci8Exception with message 'Error Code    : 904
Error Message : ORA-00904: "ID": invalid identifier
Position      : 132
Statement     : insert into "EMPLOYEES" ("FIRST_NAME", "LAST_NAME", "EMAIL", "UPDATED_AT", "CREATED_AT") values (:p0, :p1, :p2, :p3, :p4) returning "ID" into :p5
Bindings      : [Roger,Rabbit,rrabbit@somewhere.com,2021-11-04 22:13:56,2021-11-04 22:13:56,0]

【问题讨论】:

    标签: laravel eloquent database-migration


    【解决方案1】:

    当您在id 以外的表中使用主键时,您需要在模型类中指定它

    class Employee extends Model
    {
        /**
         * The primary key associated with the table.
         *
         * @var string
         */
        protected $primaryKey = 'employee_id';
    }
    

    【讨论】:

      【解决方案2】:

      id() id 方法是 bigIncrements 方法的别名。默认情况下,该方法将创建一个 id 列; $table-&gt;id();

      bigIncrements() bigIncrements 方法创建一个自动递增的 UNSIGNED BIGINT(主键)等效列:

      $table-&gt;bigIncrements('employee_id');

      【讨论】:

        猜你喜欢
        • 2014-08-16
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-06-16
        • 2019-10-04
        • 2014-12-06
        • 2015-07-28
        • 1970-01-01
        相关资源
        最近更新 更多