Laravel 查询在给定值而非变量时有效

Laravel query works when given values but not variables

好吧,这让我发疯。谁能解释一下为什么

Result::query()
    ->where('audit_id', $audit->id)
    ->where('result_type', 'App\Models\Touchpoint')
    ->whereIn('result_id', $tps)
    ->with('result')
    ->join('locations', function ($join) {
        $join->where('locations.id', $location->id);
    })
    ->join('location_weight', function ($join) {
        $join->on('results.result_id', '=', 'location_weight.weight_id')
            ->on('results.result_type', '=', 'location_weight.weight_type')
            ->on('locations.id', '=', 'location_weight.location_id');
    })
    ->get()

当 $audit->id = 1 和 $location->id = 1 时 return 没有结果,但是

Result::query()
    ->where('audit_id', 1)
    ->where('result_type', 'App\Models\Touchpoint')
    ->whereIn('result_id', $tps)
    ->with('result')
    ->join('locations', function ($join) {
        $join->where('locations.id', 1);
    })
    ->join('location_weight', function ($join) {
        $join->on('results.result_id', '=', 'location_weight.weight_id')
            ->on('results.result_type', '=', 'location_weight.weight_type')
            ->on('locations.id', '=', 'location_weight.location_id');
    })
    ->get()

return 结果是否正确?

第一个代码块应该抛出错误。您正在从父作用域 ($location) 引用一个变量,而没有将它传递给 use 语言构造

// This
->join('locations', function ($join) {
    $join->where('locations.id', $location->id);
})
// should be
->join('locations', function ($join) use ($location) {
    $join->where('locations.id', $location->id);
})