Search code examples
phplaravelmodeleloquentlaravel-5.3

Laravel 5.3: hasManyThrough relationship


I have the following situation:

location
  id - integer
  network_id - integer (FK)

network
  id - integer
  owner_id - integer (FK)

owner
  id - integer
  name - string

I have an Eloquent model for my location data. Now what I want to do, is create a RESTful API where I can retrieve the owner data through the network model.

I've tried using hasManyThrough with no luck. The model has the following relationships;

Network - Location = One to Many
Owner - network = One to One

So many locations belong to one network, and each network has one owner. This is always the case.

I've tried the following.

class Location extends Model 
{
    public function owner() {
       return $this->hasManyThrough('App\Owner', 'App\Network, 'id', 'id);
    }
}

Then return the model in my resource.

class LocationController extends Controller 
{
   public function index() {
      return [
         'data' => Location::with('network', 'owner')->take($limit)->take($offset)->get()
      ];
   }
}

I don't get an error but the model doesn't return any owner, instead just an empty array.

Can anybody help me out creating a relationship between those models using Laravel's Eloquent? I'm using Laravel 5.3.


Solution

  • Not sure whether your table structure fits to be able to use hasManyThrough

    From what I can see with the documentation you would need

    location
      id - integer
      network_id - integer
    
    network
      id - integer
      location_id - integer
    
    owner
      id - integer
      network_id - integer
      name - string
    

    Then you could use

     return $this->hasManyThrough(
                'App\Owner', 'App\Network',
                'location_id', 'network_id', 'id'
            );
    

    That being said you may be able to get it to work by trying different combinations the hasManyThrough e.g.

    return $this->hasManyThrough('App\Owner', 'App\Network, 'owner_id', 'id', 'network_id');