【问题标题】:Translate SQL query to CakePHP 3.0将 SQL 查询转换为 CakePHP 3.0
【发布时间】:2015-09-11 16:16:00
【问题描述】:

查询如下

select T.username,
sum(T.size) as totSize,
count(*) total,
count(case when T.type = 'facebook' then 1 else null end) as facebook,
count(case when T.type = 'instagram' then 1 else null end) as instagram,
count(case when T.type = 'device' then 1 else null end) as device
from (SELECT users.username, pictures.size, pictures.type from users left join pictures on pictures.user_id = users.id) as T 
group by T.username

每个“用户”都有多个“图片”。 基本上,我想做的是:

  1. 左加入用户和图片表
  2. 按类型计算图片
  3. 总结图片大小
  4. 按用户分组

SQL 查询在应用于数据库时有效,但我需要在我的 CakePHP 3.0 应用程序中表示它。 我设法使用模型关联来 LEFT JOIN 表。在用户表中:

$this->hasMany('Pictures', [
'foreignKey' => 'user_id',
'joinType' => 'LEFT'
]);

然后在我的find方法中:

$options['contain'] = ['Pictures' => function ($q) {
return $q
->select(['user_id', 'size', 'type']);}];
$options['fields'] = array('Users.username');
$query = $this->find('all', $options);

如何继续查询?如果我尝试访问包含的数据(如“Pictures.type”),我会返回 SQL 错误,指出该列不在字段列表中。 我觉得这可能是错误的方法,但我想不出其他方法。

提前致谢!

【问题讨论】:

  • 为什么是子选择,这与性能有关吗?如果没有测试,我可以想象非子查询的使用实际上可能更快。

标签: mysql sql cakephp cakephp-3.0 query-builder


【解决方案1】:

已解决

$options['contain'] = array('Users');
$query = $this->Pictures->find('all', $options);
$query->select(['Users.username', 'Users.plan', 'Users.id']);
$query->select(['sum' => $query->func()->sum('size'),])
      ->select(['count' => $query->func()->count('*'),])
      ->select(['facebook' => $query->func()
          ->count('case when type = \'facebook\' then 1 else null end'),])
      ->select(['instagram' => $query->func()
          ->count('case when type = \'instagram\' then 1 else null end'),])
      ->select(['device' => $query->func()
           ->count('case when type = \'device\' then 1 else null end'),])
      ->group('user_id');

return $query;

这允许选择连接字段为

$result = $query->all();
$result->user->username;

【讨论】:

    猜你喜欢
    • 2010-12-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-06-11
    • 2022-06-14
    • 1970-01-01
    • 2014-08-14
    相关资源
    最近更新 更多