简体   繁体   中英

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!

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM