Djave
Djave

Reputation: 9329

Laravel retrieving model with multiple `with` statments

I have a menu with products, and the products have producers.

At the moment I am doing this:

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

public static function getMenuWithProducts($month, $year){
    return self::
        where('month', '=', $month)
        ->where('year', '=', $year)
        ->with('products')
        ->get();
}

And getMenuWithProducts(11, 2014) gets a menu returned, with products. What I'd love to do is something like this (I have made this up a little – which is why its not working):

public static function getMenuWithProducts($month, $year){
    return self::
        where('month', '=', $month)
        ->where('year', '=', $year)
        ->with('products')
        ->with('producer')
        ->get();
}

But I get:

BadMethodCallException 
Call to undefined method Illuminate\Database\Query\Builder::producer()

Its worth pointing out that the producer model has

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

And the product model has

public function producer()
{
    return $this->belongsTo('Producer');
}

Am I writing my query wrong? I'm guessing I am using a non-existent function – but is there a method of adding something else in my chain to make the second with() work?

Upvotes: 0

Views: 1573

Answers (1)

Matt Burrow
Matt Burrow

Reputation: 11057

Within the with() it should be products.producer not producer

Upvotes: 2

Related Questions