Laravel 7 新增的数据库迁移(Migration)方法
id()
Laravel 6 之前的版本,我们这样将 id
列放在迁移表中,如下所示:
$table->bigIncrements('id');
随着 Laravel 7 的发布,语法将变得更加简洁 🔥
$table->id();
让我们来看看 id()
方法的定义:
/**
* Create a new auto-incrementing big integer (8-byte) column on the table.
*
* @param string $column
* @return \Illuminate\Database\Schema\ColumnDefinition
*/
public function id($column = 'id')
{
return $this->bigIncrements($column);
}
foreignId()
在 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();
});
只需要一行代码,这也太酷了吧。 🥳
让我们看看方法如何定义:
/**
* 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;
}
详细的介绍请参考最新的 文档.
本文中的所有译文仅用于学习和交流目的,转载请务必注明文章译者、出处、和本文链接
我们的翻译工作遵照 CC 协议,如果我们的工作有侵犯到您的权益,请及时联系我们。
推荐文章: