buckybadger
buckybadger

Reputation: 39

hasManyThrough() or similar database model

I have a database setup similar to this:

items
    id - integer
    user_id - int

users
    id - integer
    name - string

contacts
    id - integer
    user_id - integer
    name - string

Using Eloquent ORM how would I query for that returns the associated user, and their contacts? I'm currently using

Items::with('user')->get();

Upvotes: 1

Views: 92

Answers (2)

Jarek Tkaczyk
Jarek Tkaczyk

Reputation: 81187

It's called loading nested relations - last example on http://laravel.com/docs/eloquent#eager-loading

$items = Items::with('user.contacts')->get();

// then for example:
$item = $items->first();

$item->user; // user Model
$item->user->contacts; // Collection of Contact models

A note: there is no relation to access such relation directly. hasManyThrough won't work in this setup.

Upvotes: 1

The Alpha
The Alpha

Reputation: 146201

Models and relationship:

// User model
class User extends Eloquent {
    public function items()
    {
        return $this->hasMany('Item');
    }

    public function contacts()
    {
        return $this->hasMany('Contact');
    }
}

// Contact model
class Contact extends Eloquent {
    public function user()
    {
        return $this->belongsTo('User');
    }
}

// Item model
class Item extends Eloquent {
    public function user()
    {
        return $this->belongsTo('User');
    }
}

Usage:

$items = Item::with('user.contacts')->get(); // Result will be a collection object

$firstItem = $items->first(); //  get the first item from collection
// Or this to get first one
$firstItem = $items->get(0);  //  get the first item from collection

$firstItem->user; // Get related User Model
$firstItem->user->contacts; // get collection of Contact models

If you pass the $items to your view then you may use a loop, for example:

$items = Item::with('user.contacts')->get();
return View::make('viewname')->with('items', $items);

In your view:

@foreach($items as $item)
    {{ $item->property_name }}
    {{ $item->user->property_name }}
    @foreach($item->user->contacts as $contact)
        {{ $contact->propertyname }}
    @endforeach
@endforeach

Upvotes: 1

Related Questions