2
votes

Why do Laravel ask for a pivot table as singular, in my code? How do I fix so it call as plural?

Database tables

  • users (id, etc)
  • campaigns (id, etc)
  • campaign_users (user_id, campaign_id)

Code

My campaign model, and campaign_user model are pretty much empty, and generated by artisan. But here are my user relation to campaigns, in User model:

public function playing_campaigns()
    {
        return $this->belongsToMany('Sagohamnen\campaign\campaign');
    }

Here I call DB to get the campaigns, in which the user are part of:

$user = user::with(['playing_campaigns'])->where('id', $id)->get();

SQL error

SQLSTATE[42S02]: Base table or view not found: 1146 Table 'sagohamnen.campaign_user' doesn't exist (SQL: select campaigns.*, campaign_user.user_id as pivot_user_id, campaign_user.campaign_id as pivot_campaign_id from campaigns inner join campaign_user on campaigns.id = campaign_user.campaign_id where campaign_user.user_id in (1))

1

1 Answers

2
votes

belongsToMany takes a second parameter for the table name...

return $this->belongsToMany('Sagohamnen\campaign\campaign', 'campaign_users');

This is just the standards that Laravel assumes to try and make our lives easier.