Home > Enterprise >  Laravel - Nested Relationships
Laravel - Nested Relationships

Time:10-16

I'm learning Laravel and need to get a list of nested relationships. My foreign keys seem to be set up correctly.

products->servers->configs

Product Controller

$products = Product::with('servers')->get();

Product Model

 public function servers()
    {
        return $this->hasManyThrough(Config::class, Server::class);
    }

I'm only getting a list of servers that are the configs. Eg

products:{
  id:1,
  servers:[
    ram:16gb //this is the config not the server
 ]
}

How can I get the list of configs inside the servers inside the products? Eg

products:{
  id:1,
  server:{
    id:1,
    name:'big server',
    config:{
     ram:16gb
    }
  }
}

CodePudding user response:

In Product Modal Use hasMany Method

public function servers()
    {
        return $this->hasMany(Server::class);
    }

In Server Modal Use hasMany(for many rows get) or hasOne(for single row get) method

 public function configs()
 {
       return $this->hasMany(Config::class);
 } 

 public function config()
 {
        return $this->hasOne(Config::class);
 } 

Now In ProuctController see how to get nested relationship data

 $products = Product::with('servers.configs')->get();
  • Related