我目前可以使用查询生成器而不是 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/