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 协议,如果我们的工作有侵犯到您的权益,请及时联系我们。
所以,是这样它就知道了,我要关联的表是users???
@wongvio 同问,如果没按照约定用户表不是users,那怎么自定义 = =
@圣堂刺客 @wongvio 这还真是个问题 我去瞅瞅源码
@wongvio Laravel 还真知道你要关联 users 表,原因是根据
user_id
字段推断出来的。constrained
方法中有下面的代码:来根据
foreignId
的字段推断表名。@圣堂刺客 如果用户没有按规约来命名表名或字段名,那也没问题,
constrained
方法有个可选参数,就是你要on
的表名。@24K大白羊 谢谢,那这个用起来真的太方便了。不过最方便的还是按照约定来命名,可以在很多地方直接使用默认配置。