Laravel - 如何使用不是整数的外键?

Sta*_*bie 10 mysql laravel

我正在尝试将字符串列设置为表的主键,然后将其作为外键从另一个表中引用.这可能吗?根据文件:

Laravel assumes every table has a numeric primary key (usually named “id”) and ensures the value of this column is unique for each new row added to the table. Laravel doesn’t really work well unless each table has a numeric primary key. So, for your average Laravel application, please ensure that you define a primary key using the increments() method.
Run Code Online (Sandbox Code Playgroud)

就我而言,我不想定义一个id列,因为它没用.我想要定义的字符串列将充当主键.如果可以,我可以获得示例迁移代码段吗?

Bog*_*dan 14

这是一个老问题,但为了正确起见,我想指出在当前版本的Eloquent中你确实可以使用非数字主/外键.

你需要做的一件事是在属性设置$incrementing,以false在使用非自增ID的车型.

class Employee extends Model
{
    public $incrementing = false;

    // ...
}
Run Code Online (Sandbox Code Playgroud)

此外,迁移可以是这样的:

Schema::create('employees', function (Blueprint $table) {
    $table->string('id')->primary();
    // ...
});
Run Code Online (Sandbox Code Playgroud)


del*_*ord 3

更多关于 Eloquent 中不能为字符串的详细信息可以在此论坛存档中找到。

另外,对于评论:Eloquent 符合规范化规则。虽然 SQL 支持外键为字符串或整数,没有区别,但您应该考虑向应用程序添加整数格式键以利用 Eloquent,即使用普遍接受的整数键。