skip to Main Content

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


  1. Try the following

    $location_id_variable = 1;
    $locations = Location::find(whateverid)
       ->with([
          'employees' => function($query) use ($location_id_variable) {
            ->query->where('location_id', $location_id_variable);
        }
     ])->get()
    
    Login or Signup to reply.
  2. 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.

        $dynamicBrandLocationId = 123; // Replace this with the actual dynamic ID
        
        $locations = Location::with(['brands.employees' => fn($query) => 
                        $query->where('location_id', $dynamicBrandLocationId)])
                     ->get();
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search