MySQL Laravel 使外键唯一

MySQL Laravel making foreign key unique

在我使用 Laravel/Mysql 构建的应用程序中,我有两个 table 供用户使用。

当我注册 table“User”和“UserInfo”时,会创建。

UserInfo 有一个 FK 指向 [=25= 中的 PK ]用户 table.

现在我的 UserInfo table 中有一列设置为 unique 我这样做是为了确保该用户在 UserInfo table.

中只能有一条记录

但是否可以只使 FK 独一无二?我需要 table 之间的一对一设计。

您可以只使整数本身唯一。国外的方法只用于link那些在tableA和tableB之间的数据。

$table->integer('user_id')->unsigned()->unique();
$table->foreign('user_id')->references('id')->on('user_infos');

您可能正在寻找的是 Eloquent:Relationships 并且必须添加到您的模型中。

您可以将此添加到您的 UserInfo 模型中:

public function user()
{
    return $this->belongsTo(UserInfo::class);
}

这是您的用户模型:

    public function user_info()
{
    return $this->hasOne(User::class);
}

更多信息: https://laravel.com/docs/5.2/eloquent-relationships#defining-relationships