How can I call a dynamic variable in a subquery?
I have some relations and call them like:
$locations = Location::query()
->with('brands', function ($query) {
$query->with('employees')->where('location_id', {dynamic ID of brand location});
})
->get();
The relation in the Location.php Class:
public function brands()
{
return $this->belongsToMany(Brand::class);
}
The relation in the Brands.php Class:
public function employees()
{
return $this->belongsToMany(Employee::class);
}
Without ->where('location_id', …)
, I get all employees that belong to the brand without considering the location.
2
Answers
Try the following
By specifying ‘brands.employees’, you are telling Eloquent to load the brands relationship for each Location, and within each brands relationship, load the employees relationship. This allows you to fetch all employees associated with each brand for all the locations in a single query, which is known as eager loading.