如何在子查询中调用动态变量?
我有一些亲戚,并这样称呼他们:
$locations = Location::query()
->with('brands', function ($query) {
$query->with('employees')->where('location_id', {dynamic ID of brand location});
})
->get();
Location.php类中的关系:
public function brands()
{
return $this->belongsToMany(Brand::class);
}
Brands.php 类中的关系:
public function employees()
{
return $this->belongsToMany(Employee::class);
}
如果没有
->where('location_id', …)
,我会获得属于该品牌的所有员工,而不考虑位置。
尝试以下方法
$location_id_variable = 1;
$locations = Location::find(whateverid)
->with([
'employees' => function($query) use ($location_id_variable) {
->query->where('location_id', $location_id_variable);
}
])->get()