Laravel 8 使用foreignId()自定义外国名称

Kri*_* O. 6 laravel-7

Laravel 7 引入了使用 function 定义外键的较短版本foreignId,但我找不到为该外 ID 提供自定义名称的选项。

以“旧”方式,我们会这样写:

$table->unsignedBigInteger('user_id');
$table->foreign('user_id', 'custom_foreign_key_name')->references('id')->on('users');
Run Code Online (Sandbox Code Playgroud)

新方法:

$table->foreignId('user_id')->constrained();
Run Code Online (Sandbox Code Playgroud)

但是如何以新的方式提供“custom_foreign_key_name”?有可能吗?

小智 3

示例-您可以在 constrained() 中添加表名称:

public function up()
{
    Schema::create('tutor_payouts', function (Blueprint $table) {
        $table->id();
        $table->foreignId('tutor_id')->constrained('users');
        $table->foreignId('fee_id')->constrained();
        $table->dateTime('payout_date');
        $table->double('payout_amount', 8, 2);
        $table->timestamps();
    });
}
Run Code Online (Sandbox Code Playgroud)

参考:[https://laravel.com/docs/9.x/migrations#foreign-key-constraints][1]

如果您的表名与 Laravel 的约定不匹配,您可以通过将其作为参数传递给 constrained 方法来指定表名:

Schema::table('posts', function (Blueprint $table) {
    $table->foreignId('user_id')->constrained('users');
});
Run Code Online (Sandbox Code Playgroud)

  • 已确认,只有“旧方式”支持定义键。 (2认同)