Laravel 4 project using Eloquent ORM.
I have three tables: customers, orders and products (+ 1 pivot table order_product). Customers are tied to each other in orders. Orders are tied to many-to-many products.
Customers 1-->N Orders N<-->N Products
I would like to have a method on the Customer model that retrieves the list of products that the customer buys.
To better understand this, suppose foods are consumed.
For example, Client No. 1 may place:
- Order No. 1 for products A, B and C;
- Order No. 2 for products A, C and D;
- Order No. 3 for Products C and E;
... and the result that I want to get is a collection with products A, B, C, D and E.
Models (pseudo-encoded 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() {
St0rm source share