0
votes

There are 2 models Product and Variant where a Product hasMany Variant and a Variant belongsTo Product. Both models also contain many other relationships.

Question: How can you use Eloquent to select all Variants ->where('color','red') and also its related Product must satisfy ->where('price', '>' '50')? All the relationships of Variant in the returned resultset must be retained.

When a join is used on the Eloquent model, all relationships are lost except for the products which was joined. Eg: $variant->product->id works but not $variant->someOtherModel->id.

$variants =Variants::where('color', 'red')
    ->join('products', 'variants.product_id', '=', 'products.id')
    ->where('product.price', '>', 10)
    ->paginate(10);

foreach($variants as $variant) {
    echo $variant->product->id; //works
    echo $variant->someOtherModel->id;  // error, undefined function
}

How do you maintain all of $variant's relationship?


Each WHERE clause appears to be chained using OR rather than AND! This is crazy!

$variants = Variant::where('color', 'red')
            ->with(array('Product' => function($query) {
               if(Input::get('price')     $query->where('price', '>', 10);
               if(Input::get('brand')     $query->where('brand', Input::get('brand'));
           }))
           ->paginate(10);
1

1 Answers

0
votes

Eager load constraints may solve it:

$Variants =Variants::where('color', 'red')
->with(array(
     'Product' => function($query) {
        $query->where('price', '>', 10);
     }
    ,'OtherModel'
    ,'FooBar'
))
->paginate(10);