Victor Leal
Victor Leal

Reputation: 1065

Get results with 2 relationships Laravel

I have 3 models, let's say Product, Unit and Area.

There's a relationship between Product and Unit. A Unit may have a lot of Product.

There's another relationship between Product and Area. A Area may also have a lot of Product.

The point here is: given an Area, get all of its Product with the respective Unit.

To get all of Product given an Area is easy: $area->products(), but I would like to do $area->products->with('unit').

Is there a way to do it? Or I will have to do a foreach through the products array and querying each Unit for them?

Upvotes: 1

Views: 455

Answers (1)

user1669496
user1669496

Reputation: 33058

You use nested relationships which are defined using dot notation.

$areas = Area::with('products.unit')->get();

That will eager load products and product->units with Area.

Then you can loop through them using nested loops...

foreach($areas as $area) {
    foreach($area->products as $product) {

        // If units are returning many
        foreach($product->unit as $unit) {

        }

        // Or if there is only one unit per product
        $unit = $product->unit;
    }
}

Edit: Adding a where clause

If you need to add a where to the products, you need to separate the dot notation so you are querying for products and products.unit.

$area = Area::with(['products' => function($q) {
    $q->where('product_field', '=', 'something');
},'products.unit'])->find($area_id);

You should also check out the documentation which explains this more clearly than I probably can.

http://laravel.com/docs/5.1/eloquent-relationships#constraining-eager-loads

Upvotes: 1

Related Questions