【问题标题】:Using Laravel schema builder and migrations使用 Laravel 模式构建器和迁移
【发布时间】:2013-12-21 08:48:18
【问题描述】:

我是 Laravel PHP 框架的新手。我对 Laravel 模式构建器和迁移的工作方式感到困惑。我使用 Laravel 迁移创建了两个表。下面是我的两张表:

public function up()
    {
        Schema::create('hotels', function(Blueprint $table)
        {
            $table->increments('id');
            $table->integer('hotel_id');
            $table->string('name');
            $table->string('address')->nullable();
            $table->string('city')->nullable();
            $table->string('province')->nullable();
            $table->string('country')->nullable();
            $table->timestamps();
        });
    }

这是我的另一张桌子:

public function up()
    {
        Schema::create('rooms', function(Blueprint $table)
        {
            $table->increments('id');
            $table->integer('hotel_id');
            $table->string('name');
            $table->timestamps();
        });
    }

我的问题是如何使用外键与两个表建立关系?如果我必须使用 Schema Builder,我必须将模式文件放在哪里?

【问题讨论】:

    标签: php database laravel


    【解决方案1】:

    您可以使用 Schema Builder 在相同的迁移中执行此操作。这是您使用迁移创建外键的方式:

    public function up()
    {
        Schema::create('rooms', function(Blueprint $table)
        {
            $table->increments('id');
    
            $table->integer('hotel_id');
    
            $table->string('name');
    
            $table->foreign('hotel_id')
                  ->references('id')
                  ->on('hotels')
                  ->onDelete('cascade');
    
            $table->timestamps();
        });
    }
    

    【讨论】:

    • 我试过用你的方式。我收到此错误:[异常] SQLSTATE [42000]:语法错误或访问冲突:1072 表中不存在键列“hotel_id”(SQL:更改表rooms 添加约束rooms_hotel_id_foreign 外键(hotel_id)在删除级联时引用hotels (id)(绑定:数组())
    • 所以我必须先创建列然后添加外键?
    • 是的,但是您可以在同一个迁移中进行。外键只是一个约束+索引。
    猜你喜欢
    • 2014-03-05
    • 2015-10-06
    • 2013-12-02
    • 2022-10-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-10-22
    • 2017-12-25
    相关资源
    最近更新 更多