My goal. I have 3 Laravel models: user, campaign and campaign_players. I want to get info about a user, and also the campaigns he/she is playing.
The problem. When I run this query :
$campaigns = user::with(['campaigns_playing'])->where('id', $id)->get();
it gives me this message:
"Base table or view not found: 1146 Table 'sagohamnen.campaign_players' doesn't exist (SQL: select
sh_campaigns
.*,campaign_players
.user_id
aspivot_user_id
,campaign_players
.id
aspivot_id
fromsh_campaigns
inner joincampaign_players
onsh_campaigns
.id
=campaign_players
.id
wherecampaign_players
.user_id
in (2))"
It looks like it can't find the table name, for some reason. Do you guys have any idea what causing the problem and how to fix it?
Here are short code pieces from my models and it´s database tables.
User
protected $table = 'sh_users';
public function campaigns_playing()
{
return $this->belongsToMany('Sagohamnen\campaign\campaign', 'Sagohamnen\campaign\campaign_players', 'user_id', 'id');
}
Schema::create('sh_users', function (Blueprint $table) {
$table->increments('id')->unsigned();
$table->string('name', 255);
});
Campaign
protected $table = 'sh_campaigns';
Schema::create('sh_campaigns', function (Blueprint $table) {
$table->increments('id')->unsigned();
$table->string('name', 255);
$table->timestamps();
});
Campaign_players
protected $table = 'sh_campaign_players';
Schema::create('sh_campaign_players', function (Blueprint $table) {
$table->integer('user_id')->unsigned();
$table->integer('campaign_id')->unsigned();
$table->date('date');
$table->primary(['user_id', 'campaign_id']);
});
campaign_players
doesn't exist. From the code you have posted it seems you have named the tablesh_campaign_players
. – tam5campaign_user
in this case. – tam5campaign_user
for example, you would only need to pass one argument to yourbelongsToMany
and Laravel will imply the rest, rather than you needing to be explicit about everything. [And you can still name the methods however you see fit likecampaignsPlaying
]. But again, just a suggestion, do what makes sense for your case :) – tam5