我在拉勒维尔的外键上工作。如何在表上添加外键很简单。但是,如果表可以包含多个外键,例如:
有几张桌子:
Building
id
name
companies(can be more than one)
其他表格如下:
Companies
id
name
正如我从良好实践中所记得的,我应该使用列创建其他表,如building_company
building_id
company_id
如果它是好的方式,这个第三表的模型应该如何命名和使用,或者在Laravel中有其他的解决方案用于多个FKs?
谢谢
发布于 2019-11-25 10:32:39
建筑表格
public function up()
{
Schema::create('Building', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->string('companies');
$table->timestamps();
});
}
公司表
public function up()
{
Schema::create('Companies', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->timestamps();
});
}
building_company表
public function up()
{
Schema::create('building_company', function (Blueprint $table) {
$table->increments('id');
$table->integer('building_id')->references('id')->on('Building')->onDelete('cascade');
$table->integer('company_id')->references('id')->on('Companies')->onDelete('cascade');
$table->timestamps();
});
}
发布于 2019-11-25 10:29:18
建立n:n关系
Schema::create('building_companies', function (Blueprint $table) {
$table->integer('company_id')->unsigned();
$table->integer('building_id')->unsigned();
$table->foreign('building_id')
->references('id')
->on('building')
->onDelete('cascade');
$table->foreign('company_id')
->references('id')
->on('companies')
->onDelete('cascade');
});
https://stackoverflow.com/questions/59029584
复制相似问题