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

时间:2014-07-24 22:54:47

标签: 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.

在我的情况下,我不想定义id列,因为它没用。我想要定义的字符串列将充当主键。如果可以,我可以获得示例迁移代码段吗?

2 个答案:

答案 0 :(得分:14)

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

您需要做的一件事是在使用非自动增量ID的模型上将属性$incrementing设置为false

class Employee extends Model
{
    public $incrementing = false;

    // ...
}

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

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

答案 1 :(得分:2)

可以在此forum archive中找到更多详细信息,为什么它不能成为Eloquent中的字符串。

此外,评论:Eloquent符合normalization rules。虽然SQL支持外键是字符串或整数没有区别,你应该考虑在你的应用程序中添加一个整数格式键来使用Eloquent,即使用普遍接受的整数键。