Laravel how to store more foreign data together with the foreign key (on creation)

28 Views Asked by At

I have a many to many relation ship between my Job and Company models.

Here is a small part of the migration that handles the relation:

$table->bigInteger('company_id')->unsigned();
$table->foreign('company_id')->references('id')->on('companies')->onDelete('cascade');
$table->string('company_name')->references('name')->on('companies')->onDelete('cascade');

The first two lines create the foreign key. After writing some more code I came to the conclusion that I use a companies name a lot when I need to use the Job model, so now I want to store company_name in the Job model together with the foreign key. The foreign key is set on creation, can I do this with the company_name as well? The third line did not do the trick:

$table->string('company_name')->references('name')->on('companies')->onDelete('cascade');

Laravel says: General error: 1364 Field 'company_name' doesn't have a default value.

1

There are 1 best solutions below

1
Razvan Preda On

Add unique index on name in companies tabele. To work as expected, companies table must contain unique name values

$table->unique('name');

$table->string('company_name');

$table->foreign('company_name')
    ->references('name')
    ->on('companies')
    ->onDelete('cascade');