Is there any way to get the ID inside the query?
I don't know how to explain this fluently, but I'm trying to grab the product options for each product, but i need to use the product ID inside the with statement to do that.
Something like that but $idOfModel
should obviously be the id of each product.
$products = Product::with('attributes', function($q) {
$q->with('product_options', function($q) {
$q->where('product_id', $idOfModel)->with('variable', function($q) {
$q->where('product_id', $idOfModel);
});
})->groupBy('id');
})->take(10)->get();
CodePudding user response:
The goal is to take for each product their options with their variables/values
so basically you just have to define relations correctly and eloquent will do everything for you (even nested eager loading)
// Product model
// relations that fits your schema
public function attributes(){
return $this->relationName(Attribute::class);
}
public function productOptions(){
return $this->relationName(ProductOption::class);
}
//ProductOption model
public function vaiable(){
return $this->relationName(Variable::class);
}
// then in controller
$products = Product::with(['attributes', productOptions.variable'])
->take(10)
->get();
CodePudding user response:
You have access your productId
using your first Builder
like below.
$products = Product::with('attributes', function($q1) {
$q1->with('product_options', function($q2) use ($q1) {
$q2->where('product_id', $q1->id)->with('variable', function($q3) use ($q1) {
$q3->where('product_id', $q1->id);
});
})->groupBy('id');
})->take(10)->get();