【问题标题】:Laravel - Stop multiple queries chainingLaravel - 停止多个查询链接
【发布时间】:2014-12-09 05:14:56
【问题描述】:

我目前有使用查询生成器而不是 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 的一个实例有关,但我不确定?

【问题讨论】:

  • 只使用有意义的名称。 $this->devices 不是 devices,而是 Query\Builder 实例,因此显然您需要 2 个这样的实例来进行单独的查询。

标签: php mysql sql laravel laravel-4


【解决方案1】:

怎么样:

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

【讨论】:

  • 虽然这行得通,但我希望能够执行上述方法,然后我可以在声明表格的位置之后轻松附加->remember(30) 之类的内容......如果我必须这样做,这并不理想它很多次,并且一遍又一遍地命名同一个表。
  • 为编辑干杯。所以克隆工作:) 可惜我不能将所有变量分配给一个克隆(我很懒)。
  • 你也可以创建私有方法来获取设备表并调用$this->devicesTable()->where(...)
猜你喜欢
  • 1970-01-01
  • 2016-05-31
  • 1970-01-01
  • 2015-10-06
  • 2023-01-31
  • 1970-01-01
  • 1970-01-01
  • 2019-11-10
  • 2014-09-10
相关资源
最近更新 更多