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;
    }

HuNmjUceci.png!large

详细的介绍请参考最新的 文档.

本文中的所有译文仅用于学习和交流目的,转载请务必注明文章译者、出处、和本文链接
我们的翻译工作遵照 CC 协议,如果我们的工作有侵犯到您的权益,请及时联系我们。

原文地址:https://dev.to/zubairmohsin33/new-migrat...

译文地址:https://learnku.com/laravel/t/41691

本文为协同翻译文章,如您发现瑕疵请点击「改进」按钮提交优化建议
《L05 电商实战》
从零开发一个电商项目,功能包括电商后台、商品 & SKU 管理、购物车、订单管理、支付宝支付、微信支付、订单退款流程、优惠券等
《L03 构架 API 服务器》
你将学到如 RESTFul 设计风格、PostMan 的使用、OAuth 流程,JWT 概念及使用 和 API 开发相关的进阶知识。
讨论数量: 6
$table->foreignId('user_id')->constrained();

所以,是这样它就知道了,我要关联的表是users???

4年前 评论

@wongvio 同问,如果没按照约定用户表不是users,那怎么自定义 = =

4年前 评论

@wongvio Laravel 还真知道你要关联 users 表,原因是根据 user_id 字段推断出来的。 constrained 方法中有下面的代码:

Str::plural(Str::before($this->name, '_id'))

来根据 foreignId 的字段推断表名。

4年前 评论
wongvio 4年前

@圣堂刺客 如果用户没有按规约来命名表名或字段名,那也没问题,constrained 方法有个可选参数,就是你要 on 的表名。

$table->foreignId('user_id')->constrained($tableName);
4年前 评论

@24K大白羊 谢谢,那这个用起来真的太方便了。不过最方便的还是按照约定来命名,可以在很多地方直接使用默认配置。

4年前 评论

讨论应以学习和精进为目的。请勿发布不友善或者负能量的内容,与人为善,比聪明更重要!