新来的拉勒维尔
链接表时,foreignId()和unsignedBigInteger()有什么区别?
$table->unsignedBigInteger('user_id');
$table->foreignId('user_id');
我都试过了,他们都成功了。
根据文档的说法:
foreignId
方法是unsignedBigInteger
的别名
但是别名是什么意思呢?这是否意味着他们是一样的?
PS:我没有在文档中使用代码,而是只使用
$table->unsignedBigInteger('user_id');
和/或
$table->foreignId('user_id');
发布于 2020-04-02 23:44:38
如果您查看一下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。
发布于 2020-04-02 23:47:05
直到Laravel 6,我们必须定义外键约束,例如
Schema::table('posts', function (Blueprint $table) {
$table->unsignedBigInteger('user_id');
$table->foreign('user_id')->references('id')->on('users');
});
这是Laravel 7的语法
Schema::table('posts', function (Blueprint $table) {
$table->foreignId('user_id')->constrained();
});
发布于 2020-04-02 23:41:48
是的别名意味着是一样的。
https://stackoverflow.com/questions/61002912
复制相似问题