Issue with Many to Many relationship

Hey man, nice tutorial. I’m facing an issue in my project, there is this table that has a many to many relationship with 3 other tables. The relationship with the first table worked, but it doesn’t allow me to use the same column name in the other tables. And I’m having issues attaching to the pivot table. For example, I have a User with a many to many relationship with Client and Agent => A user can have many clients and vice versa. so my pivot table for client_user looks like =>
this.create(“client_user”, table => {
table.increments();
table
.integer(“client_id”)
.unsigned()
.index(“client_id”);
table
.integer(“user_id”)
.unsigned()
.index(“user_id”);
table
.foreign(“client_id”)
.references(“clients.id”)
.onDelete(“cascade”);
table
.foreign(“user_id”)
.references(“users.id”)
.onDelete(“cascade”);
table.timestamps();
});

but I’m not allowed to use user_id as a column in the pivot table for agent_user =>

this.create("agent_user", table => {
  table.increments();
  table
    .integer("agent_id")
    .unsigned()
    .index("agent_id");
  table
    .integer("user_agent")
    .unsigned()
    .index("user_agent");
  table
    .foreign("agent_id")
    .references("agents.id")
    .onDelete("cascade");
  table
    .foreign("user_agent")
    .references("users.id")
    .onDelete("cascade");
  table.timestamps();
});

I don’t know if this helps or not but the way I setup foreign keys (which seems to work) is as so

table.integer('agent_id').unsigned().references('id').inTable('agents').onDelete('cascade')

Then I would set up my relationships in the models

1 Like

it worked @SouthRibbleTech . Thanks