0

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

justsimpleuser
  • 149
  • 1
  • 14
  • Take a look https://stackoverflow.com/questions/31415213/how-i-can-put-composite-keys-in-models-in-laravel-5 – Harry Nov 25 '19 at 10:38

3 Answers3

1

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');

});
hemant
  • 156
  • 1
  • 6
1

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();
        });
    }
VIKAS KATARIYA
  • 5,867
  • 3
  • 17
  • 34
0

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)

N69S
  • 16,110
  • 3
  • 22
  • 36