我是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在相同的迁移中完成此操作。这就是使用迁移创建外键的方法:
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();
});
}