Search code examples
laraveleloquenteloquent-relationship

Eloquent Intermediate Tabel with None Standard ID Column


While creating my database according to the eloquent standard, I ran into the problem that my table_name and id column name combined would be longer as 64 characters.

very_long_table_name.very_long_column_name_id

So I used a shorter column name as the foreign key in my Intermediate Table.

Migration file:

$table->unsignedBigInteger('short_id');
$table->foreign('short_id')->references('id')->on('very_long_table_name');

That worked fine, yet now I would like to insert a connection

Seeder.php:

$x->very_long_table_name()->attach($other_table_name->id);

I get the error: SQLSTATE[42S22]: Column not found: 1054 Unknown column 'very_long_column_name_id' in 'field list' (SQL: insert into very_long_table_name (just_an_id, very_long_column_name_id) values (1, 1))

What I would want is that it would use the column short_id instead of very_long_column_name_id to insert this, is there any cool way to fix this? or do I need to insert and query the connection manually if I keep the long names?


Solution

  • Like @Tim points out in the comments this needs to be done in the Model VeryLongTableName.php where you define the relationship:

    public function very_long_table_name() {
      return $this->belongsToMany(Model::class, 'very_long_table_name', 'local_id', 'short_id');
    }