laravel - foreignId() 和 unsignedBigInteger() 之间的区别

h-k*_*kys 7 php database laravel

Laravel 新手

链接表时foreignId()和unsignedBigInteger()有什么区别

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

我已经尝试了两者,它们都有效。

根据文档,它说:

foreignId方法是一个别名unsignedBigInteger

别名是什么意思?这是否意味着它们是相同的?


PS:我没有使用文档中的代码,而只是

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

和/或

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

Oct*_*tet 10

如果您查看 Blueprint.php,您将看到两种方法:

 /**
 * Create a new unsigned big integer (8-byte) column on the table.
 *
 * @param  string  $column
 * @param  bool  $autoIncrement
 * @return \Illuminate\Database\Schema\ColumnDefinition
 */
public function unsignedBigInteger($column, $autoIncrement = false)
{
    return $this->bigInteger($column, $autoIncrement, true);
}

/**
 * Create a new unsigned big integer (8-byte) column on the table.
 *
 * @param  string  $column
 * @return \Illuminate\Database\Schema\ForeignIdColumnDefinition
 */
public function foreignId($column)
{
    $this->columns[] = $column = new ForeignIdColumnDefinition($this, [
        'type' => 'bigInteger',
        'name' => $column,
        'autoIncrement' => false,
        'unsigned' => true,
    ]);

    return $column;
}
Run Code Online (Sandbox Code Playgroud)

因此,默认情况下它使用“bigInteger”列的类型,“unsigned”设置为true。最后,他们是一样的。

唯一的区别是,使用“unsignedBigInteger”,您可以控制 $autoIncrement 是否设置为 true 或 false,而不是 foreignId


小智 8

在 Laravel 6 之前,我们需要定义外键约束,如

Schema::table('posts', function (Blueprint $table) {
    $table->unsignedBigInteger('user_id');

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

这就是 Laravel 7 语法

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