【问题标题】:Foreign keys on laravellaravel 上的外键
【发布时间】:2020-03-20 14:41:26
【问题描述】:
我正在尝试在 Laravel 上使用外键。如何在表上添加外键非常简单。但是如果表可以包含多个外键,例如:
有桌子:
Building
id
name
companies(can be more than one)
其他表是:
Companies
id
name
正如我从良好实践中所记得的那样,我应该使用列创建其他表,例如 building_company
building_id
company_id
如果方法好的话,这第三张表的模型应该如何命名和使用,或者在 Laravel 中可能有其他解决多个 FK 的方法?
谢谢
【问题讨论】:
标签:
mysql
laravel
foreign-keys
key
【解决方案1】:
建筑桌
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();
});
}
【解决方案2】:
建立 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');
});
【解决方案3】:
你不要在 Laravel 中为数据透视表使用 Model::class,因为它不支持复合主键,
你可以声明一个Pivot::class (Illuminate\Database\Eloquent\Relations\Pivot)
但是大多数时候(特别是如果只有 ids)你没有声明数据透视类,你使用了两个主要模型之间的多对多(belongsToMany())关系(在你的情况下是Building 和Company)