php - Laravel - 停止多个查询链接

标签 php mysql sql laravel laravel-4

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

假设我想统计我的一张表中拥有 iOS token 的用户数量,然后是拥有 android token 的用户数量。

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

关于php - Laravel - 停止多个查询链接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26360331/

相关文章:

php - 这是获取 1024 到 65535 之间随机数的正确方法吗?

mysql - 以 HH :MM in MySQL for Performance 格式存储时间的最佳方式

sql - 恢复数据库SQL Server查询

PHP 多页面点击计数器自动生成

php - 带有 mysql 池的 node.js(集群)的基准测试性能 : Lighttpd + PHP?

MySQL 变量替换

c# - 如何使用自动增量列将集合保存为用户定义的数据类型?

SQL Server : how to insert a record into related table during an update?

php - 使用php在mysql语句中传递一个数组

PHP代码在搜索引擎中的书写问题