1
votes

So using Laravel 4, I have a Sales table that has a many to many relationship with a Products table, and it also has a one to many relation with a Customers table.

I set up my models as follows:

class Sale extends Eloquent {
...
    public function products(){
        return $this->belongsToMany('Product');
    }
    public function customers(){
        return $this->belongsTo('Customer');
    }
}

class Product extends Eloquent {
...
    public function sales(){
        return $this->belongsToMany('Sale');
    }
}

class Customer extends Eloquent {
...
    public function sales(){
    return $this->hasMany('Sale');
    }
}

What I want to do is return the data of all sales, including the data of each product included in each sale and the data of the customer that bought it.

In my SalesController I'm using eager loading to query my data like this:

public function index()
{
    return Sale::with('products', 'customers')->get();
}

It returns an object with the Sale data, the Product data, but the Customer data is null.

How can I achieve this using Eloquent (or a custom query)?

EDIT

This is the object string it returns:

[{"id":1,"customer_id":1,"date":"2013-11-21","status":1,"created_at":"0000-00-00 00:00:00","updated_at":"0000-00-00 00:00:00","products":[{"id":1,"name":"Monitor","price":50,"status":1,"created_at":"0000-00-00 00:00:00","updated_at":"0000-00-00 00:00:00","pivot":{"sale_id":1,"product_id":1,"custom_price":25,"order":1}}],"customers":null}]
1
As I see you are doing it right. I think problem lies else where.tharumax
I'm a bit confused by your code. In sales model, shouldn't it be customer in singular to represent a 1:n relationship?Manuel Pedrera
Can we see the data definitions? Does the sales table have a customer_id field?J.T. Grimes
@J.T.Grimes: My Sales table has: id, customer_id, date, status Customer has basic customer data, and Product has basic product data.Pablo.mtz
@ManuelPedrera I changed it to singular and it worked! Awesome!! Can you put your comment as answer so I can accept it as correct??Pablo.mtz

1 Answers

0
votes

Try changing your customers relationship to singular:

class Sale extends Eloquent {
...
    public function products(){
        return $this->belongsToMany('Product');
    }
    public function customer(){ // <- here
        return $this->belongsTo('Customer');
    }
}

(Moved from comments to answer)