cakephp3-无法显示值的计数

时间:2017-05-18 07:58:36

标签: php cakephp cakephp-3.0

我试图显示一个房间里的用户数量。但是当我尝试这样做时,我会收到错误。

这是关系

Rooms has many users.
Rooms belong to groups.

public function initialize(array $config)
{
    parent::initialize($config);

    $this->table('rooms');
    $this->displayField('name');
    $this->primaryKey('id');

    $this->belongsTo('Groups', [
        'foreignKey' => 'group_id'
    ]);
    $this->hasMany('Users', [
        'foreignKey' => 'room_id'
    ]);
}

为实现这一目标,我写了一个控制器功能,如下所示:

public function index()
{
   $this->loadComponent('Prg');
   $this->Prg->commonProcess();
   $params = $this->Prg->parsedParams();
   $this->paginate = [
    'limit'  => 25,
    'order' => ['id' => 'ASC'], 
    'finder' => ['RoomsList' =>['filter'=> $params]],
    'sortWhitelist' => ['Rooms.id','Rooms.name'],
    'extraOptions' =>['params' => $params]
    ];

   $rooms = $this->paginate($this->Rooms);
   $this->set(compact('rooms'));
   $this->set('_serialize', ['rooms']);
}

此功能对可用房间列表进行分页。这工作正常,但现在当我试图显示每个房间的用户数时,它会抛出错误。

我修改了模型函数,如下所示:

public function findRoomsList(Query $query, array $options)
{ 
    $query->select(['id','name','modified','created'])
    ->contain([
                    'Groups'=> function ($query) {
                        return $query->select(['id','name']);
                    },
                    'Users' => function($query){
                        return $query->select(['status','full_name']);
                        //want to fetch total number of users
                    }
            ]);

    echo $query;
    return $query;
}

现在我收到了这个错误:

You are required to select the "Users.room_id" field(s) 

有谁能告诉我我在这里犯的错误?我是CakePHP3的新手。

0 个答案:

没有答案