Laravel - 如何使用非整数的外键作为主键?

16

我正在尝试将一个字符串列设置为表的主键,然后从另一个表中引用该主键作为外键。这种做法可行吗? 根据文档:

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列,因为它是无用的。我想要定义的字符串列将作为主键。如果可能的话,我可以得到一个迁移片段示例吗?

@Strawberry - 这是不是意味着我需要定义一个整数 id - StackOverflowNewbie
如果你想使用 Laravel,那么我猜你需要按照 Laravel 告诉你的去做! - Strawberry
2个回答

21

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

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

class Employee extends Model
{
    public $incrementing = false;

    // ...
}

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

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

这样就解决了在protected $primaryKey ='slug';的模型中返回0的问题。 - Jeff Puckett

3

请查看此论坛存档,了解更多关于为什么在Eloquent中不能使用字符串的详细信息。

此外,对于评论:Eloquent符合规范化规则。尽管SQL支持将外键作为字符串或整数进行处理没有区别,但您应该考虑向应用程序添加整数格式键以利用Eloquent,即使用通常被接受的整数键。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接