Reputation: 169
I'm trying to work with foreign keys on Laravel. It's quite simple how to add foreign key on table. But if table can contain more than one foreign key, for example:
There is tables:
Building
id
name
companies(can be more than one)
and other table is:
Companies
id
name
As I remember from good practices, I should create other table like building_company with columns
building_id
company_id
If it's in good way, how Model of this 3rd table should be named and used, or maybe in Laravel there is other solutions for multiple FKs?
Thank you
Upvotes: 0
Views: 255
Reputation: 6005
Building table
public function up()
{
Schema::create('Building', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->string('companies');
$table->timestamps();
});
}
Companies table
public function up()
{
Schema::create('Companies', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->timestamps();
});
}
building_company table
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();
});
}
Upvotes: 1
Reputation: 17206
You dont use a Model::class
for a pivot table in Laravel because it doesn't support composite primary key,
You can declare a Pivot::class
(Illuminate\Database\Eloquent\Relations\Pivot
)
But most of the times (especially if there is only the ids) you dont declare the pivot class, You use ManyToMany (belongsToMany()
) relation between the two main models (Building
& Company
in your case)
Upvotes: 0
Reputation: 154
Establish n:n relationship
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');
});
Upvotes: 1