laravel在不应该的时候给我一个对象

时间:2015-10-08 15:38:43

标签: php laravel laravel-5.1 query-builder

所以我在投资者模型上有以下范围:

public function scopeCountUsersInRegionForCompany(Builder $query, $companyName, $regionCode)
{
    return $query->select('users.*')
                 ->join('user_profile', 'user_profile.user_id', '=', 'users.id')
                 ->join('investments', 'users.id', '=', 'investments.user_id')
                 ->join('offerings', 'investments.offering_id', '=', 'offerings.id')
                 ->join('companies', 'offerings.company_id', '=', 'companies.id')
                 ->where('companies.slug', '=', $companyName)
                 ->where('user_profile.region', '=', $regionCode)
                 ->count();

}

用于以下背景:

public function regionCountForCompany($slug)
{
    $regions = [];
    $totalUsersForCompany = Investor::countUsersForCompany($slug);

    if ($totalUsersForCompany === 0) {
        return [];
    }

    foreach ($this->getAllRegions() as $regionCode => $regionName) {

        $regions[$regionName] = (Investor::countUsersInRegionForCompany($slug, $regionCode) / Investor::countUsersForCompany($slug)) * 100;
    }


    if (max($regions) > 0) {
        return $regions;
    } else {
        return [];
    }
}

注意每个循环:

    foreach ($this->getAllRegions() as $regionCode => $regionName) {

        $regions[$regionName] = (Investor::countUsersInRegionForCompany($slug, $regionCode) / Investor::countUsersForCompany($slug)) * 100;
    }

以下电话:

Investor::countUsersInRegionForCompany($slug, $regionCode)

将返回1然后每隔一段时间返回:Object of class Illuminate\Database\Eloquent\Builder could not be converted to int如果我这样做:var_dump(is_object(Investor::countUsersInRegionForCompany($slug, $regionCode)))它的错误一次,那么每隔一次它就被调用为真。

这是导致此问题的唯一范围。但是,如果我在范围内进行var转换以获取变量$query而不是像你看到我做的那样返回它,它会以int形式返回。

如果我在浏览器中点击调用此特定代码集的终点,则所有这些都有效,没有关于对象或任何对象的错误。测试如下:

public function it_should_return_region_count_for_investors() {
    $this->createInvestment();

    $investor = factory(User::class)->create([
        'role_id' => 4
    ]);

    $response = $this->actingAs($investor)
                     ->call('GET', 'api/v1/investors-signedup-by-jurisdiction/');

    $this->assertNotEmpty(json_decode($response->getContent()));
}

响应回复为:Object of class Illuminate\Database\Eloquent\Builder could not be converted to int(它实际上会显示带有此消息的html laravel错误页面)

发生了什么事?

1 个答案:

答案 0 :(得分:5)

这是因为Laravel有点愚蠢的检查。当它调用范围时,它会检查函数必须返回的内容,并为链接添加后备:

return call_user_func_array([$this->model, $scope], $parameters) ?: $this;

所以当你的函数返回1时 - 三元运算符等于true并且结果返回,当它返回0时 - 三元运算符失败,而你得到this

我建议你不要从范围返回结果。完成修改查询,而不是返回结果。将count()放在范围之外,如

Investor::usersInRegionForCompany($slug, $regionCode)->count()