user3844579 user3844579 - 26 days ago 5
MySQL Question

Laravel 5.3 relationship issue

class Game extends Model
{
public function regions() {
return $this->hasMany('Region');
}
public function servers() {
return $this->hasMany('Server');
}
}

class Region extends Model
{
public function servers() {

return $this->belongsToMany('Server');
}
}

class Server extends Model
{
public function regions() {
return $this->hasMany('Region');
}
}


Every game has a server and every server has a region.
I'm trying to get all the games, its server and its region:game=Game::with('regions', 'regions.servers')->find($id);

I get an error, that: Base table or view not found: 1146 Table 'region_server' doesn't exist (SQL: select
servers
.*,
region_server
.
region_id
as
pivot_region_id
,
region_server
.
server_id
as
pivot_server_id
from
servers
inner join
region_server
on
servers
.
id
=
region_server
.
server_id
where
region_server
.
region_id
in (4, 5)

What am I doing wrong?
Thanks!

Answer

Your relationships seems to be broken, you should do it like this:

class Game extends Model
{
    public function regions() {
        return $this->hasMany('Region');
    }
    public function servers() {
        return $this->hasMany('Server');
    }
}

class Region extends Model
{
    public function servers() {
      return $this->hasMany('Server');
    }
}

class Server extends Model
{
    public function region() {
        return $this->belongsTo('Region');
    }
}

According to the above relationships,

  • Every Game has many Servers.
  • Every Server belongs to a Region
  • Every Region has many Servers

Hope this helps