首页 > 解决方案 > laravel - foreignId() 和 unsignedBigInteger() 之间的区别

问题描述

Laravel 新手

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

$table->unsignedBigInteger('user_id');
$table->foreignId('user_id');

我都试过了,它们都奏效了。

根据文档,它说:

foreignId方法是一个别名unsignedBigInteger

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


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

$table->unsignedBigInteger('user_id');

和/或

$table->foreignId('user_id');

标签: phpdatabaselaravel

解决方案


如果您查看 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;
}

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

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


推荐阅读