如何使用具有默认值的 foreignId-constrained?

How to use foreignId-constrained with default value?

刚刚从视频教程中注意到Laravel有这个foreignId-constrained。所以我尝试将我的代码从 method.1 更改为 method.2,table 已迁移,但是当我尝试 db:seed,默认值不起作用(returns 下面的错误)。

(方法 1)

$table->unsignedBigInteger('status_id')->default(1);

$table->foreign('status_id')
    ->references('id')
    ->on('user_statuses');

(方法 2)

$table->foreignId('status_id')->constrained('user_statuses')->default(1);

(使用方法 2 返回错误)

SQLSTATE[HY000]: General error: 1364 Field 'status_id' doesn't have a default value (SQL: insert into users (username, password) values (admin, y$S ZUIglBQG/HhS/18zn41GOcH8f.hZaNewmyoGJBfDQchfC6OWdx26))

According to the documentation,您调用的方法顺序错误:

Any additional column modifiers must be called before the constrained method

$table->foreignId('status_id')->default(1)->constrained('user_statuses');