Laravel-停止多个查询链接


Laravel - Stop multiple queries chaining

我目前可以使用查询生成器而不是Eloquent从数据库中获取一些统计信息。

比方说,我想统计拥有iOS代币的用户数量,然后在我的一个表中拥有android代币的用户。

class Connection {
    public function __construct()
    {
        return $this->db = DB::connection('database_one');
    }
}
class Statistics extends Connection {
    public function devices()
    {
        $this->devices = $this->db->table('users_devices');
        $arr = [
            'ios' => $this->devices->where('ios_push_token', '!=', '')->count(),
            'android' => $this->devices->where('android_push_token', '!=', '')->count(),
        ];
        return $arr;        
    }
}

获取ios设备的查询是正确的:

select count(*) as aggregate from `users_devices` where `ios_push_token` != ?
array (size=1)
      0 => string '' (length=0)

然而,我遇到了android值的问题,查询尝试执行:

select count(*) as aggregate from `users_devices` where `ios_push_token` != ? and `android_push_token` != ?
array (size=2)
  0 => string '' (length=0)
  1 => string '' (length=0)

它似乎将where子句从第一个查询链接到第二个查询,依此类推,因为它的多个实例给了我不正确的数据。

我认为这与使用DB::connection的一个实例有关,但我不确定?

怎么样:

class Statistics {
    public function devices()
    {
        $arr = [
            'ios' => DB::table('users_devices')->where('ios_push_token', '!=', '')->count(),
            'android' => DB::table('users_devices')->where('android_push_token', '!=', '')->count(),
        ];
        return $arr;        
    }
}

或者克隆对象:

class Connection {
    public function __construct()
    {
        return $this->db = DB::connection('database_one');
    }
}
class Statistics extends Connection {
    public function devices()
    {
        $this->devices = $this->db->table('users_devices')->remember(30); // etc.
        $ios = clone $this->devices;
        $android= clone $this->devices;
        $arr = [
            'ios' => $ios->where('ios_push_token', '!=', '')->count(),
            'android' => $android->where('android_push_token', '!=', '')->count(),
        ];
        return $arr;        
    }
}