Laravel - 停止多个查询链接

时间:2014-10-14 12:00:23

标签: php mysql sql laravel laravel-4

我目前有使用查询生成器从我的数据库中获取一些统计信息的功能,而不是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的一个实例有关,但我不确定?

1 个答案:

答案 0 :(得分:3)

怎么样:

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;        
    }
}