Question: Laravel 4 Project, using Eloquent ORM.

I have three tables: customers, orders and products (+ 1 pivot table order\_product). Customers are linked one-to-many to Orders. Orders are linked many-to-many to Products.

```
Customers  1-->N  Orders  N<-->N   Products

```

I would like to have a method on Customer model that retrieves a list of products that customer is buying.

To better understand this, assume products are consumable.

For example Customer #1 can place:

* Order #1 for Products A, B and C;
* Order #2 for Products A, C and D;
* Order #3 for Products C and E;

...and the result I want to retrieve is a Collection with Products A, B, C, D and E.

Models are (pseudo-coded on the fly):

```
class Product extends Eloquent {

    public function orders()
    {
        return $this->belongsToMany('Order');
    }

}

class Orders extends Eloquent {

    public function customer()
    {
        return $this->belongsTo('Customer', 'customer_id');
    }

    public function products()
    {
        return $this->belongsToMany('Product');
    }

}

class Customers extends Eloquent {

    public function orders()
    {
        return $this->hasMany('Orders', 'customer_id');
    }

    public function products()
    {
        // What to put here ???
    }

}

```

Answer: 
This is a Many-to-Many relationship, but with the **Orders** table as the pivot table. 

```
class Customers extends Eloquent {

    public function orders()
    {
        return $this->hasMany('Orders', 'customer_id');
    }

    public function products()
    {
        return $this->belongsToMany('Products', 'orders', 'customer_id', 'product_id');
    }
}

```

I've included the last two parameters, but if you follow the singular\_id pattern they can be left out. 

It's possible to receive distinct Product models like this:

```
public function products()
{
    return $this->belongsToMany('Products', 'orders', 'customer_id', 'product_id')
        ->distinct();
}

```
I can't think of easy relation method for this one, but here's a workaround:

```
$productsIds = DB::table('customers')
    ->leftJoin('orders', 'orders.customer_id', '=', 'customers.id')
    ->join('order_item', 'order_item.order_id', '=', 'orders.id')
    ->leftJoin('items', 'order_item.item_id' , '=', 'items.id')
    ->distinct()
    ->get(['items.id']);

$productsIds = array_fetch($productsIds, 'id');

$productsCollection = Product::whereIn('id', $productsIds);

```