3

我正在使用此查询来获取所有数据,但我还需要在其中添加它返回的行数。

这是我的代码:

function getUsers($id){
    $users = $this->User->find('all', array('condition'=>array('my_id'=>$id)));
    $numUsers = sizeof($users);
    $users['User']['Total']= $numUsers;
    echo  json_encode($users);
}

包含用户的$dArray所有数据,但我也希望它告诉我那里有多少用户。

我在想我会在 User 对象中获取数据,但这就是我们给我的

Object
0: Object
1: Object
2: Object
3: Object
4: Object
5: Object
User: Object
Total: 6


instead of adding it to the 

0: Object
Company: Object
Group: Object
Team: Array[0]
User: Object
company_id: "20"
created: "2012-04-15 17:35:51"
email: "dd@gmail.com"
expiration_date: "2012-04-15 17:35:00"
firstname: "jason"
grants_id: null
group_id: "1"
id: "1"
lastname: "brawar"
modified: "2012-04-23 14:25:48"
name: null
password: "203e686b6a6938648ddd3eb0a8d95988ac638596"
phone: "abcd"
status: "Active"
type: null
username: "asim"
Total: 1
4

4 回答 4

11

也许你正在寻找这个...

$conditions = array('somecondition' => $someCond);
$totalUsers = $this->User->find('count', array('conditions' => $conditions));

http://book.cakephp.org/2.0/en/models/retrieving-your-data.html#find-count

好的,现在如果要获取每个用户的元素总数,应该执行以下操作:

$users = $this->User->find('all');
foreach($users as $key => $user)
$ElementsForEachUser[$key]['totalRows'] = sizeof($user['User']);
于 2012-05-10T02:30:47.723 回答
8

无需在查询中执行此操作 - 只需使用 PHP:

<?php
$this->User->recursive=-1;
$users = $this->User->find('all', array('conditions'=>array('my_id'=>$id)));
$numUsers = sizeof($users);

这将为您提供主要项目(即用户)的数量,因为您想通过递归或可包含的任何“额外”数据将嵌套在每个单独的用户数组中。

于 2012-05-10T01:54:20.440 回答
2
$conditions = array('somecondition' => $someCond);
$totalUsers = $this->User->find('count', array('conditions' => $conditions));
于 2013-04-04T09:56:52.437 回答
0
  1. 如果您已经获取了行 - sizeof($users);,就像其他答案中提到的那样。

  2. 但是,如果您想执行 sql COUNT从 Cake 3 开始,您可以->count()在查询中使用:

$query = $this->User->find('all');
$number = $query->count();
于 2020-04-07T01:58:25.167 回答