1

我有以下关系:

class Platformuser extends AppModel {
 public $hasAndBelongsToMany = array(
    'Service'
 );
}    

class Service extends AppModel {
 public $hasAndBelongsToMany = array(
    'Platformuser'
 );
}

我正在 PlatformusersController 上执行操作,以使用以下查询获取与此用户关联的服务:

$this->Platformuser->find('all', array(
 'conditions' => array('Platformuser.id' => $userId),
));

它返回有关 Platformuser/Service 的所有内容,我只想要服务的数据:

array(
(int) => array(
    [Platformuser] => array(
        [id] => [1]
        [name] => [Domingo]
    ),
    [Service] => array(
        (int) 0 => array(
                [id] => [1]
                [name] => [dropbox],
                [PlatformusersService] => array(
                   [id] => [1],
                   [platformuser_id] => [1],
                   [service_id] => [1],
                   [modified] => [2013-10-10 00:00:00],
                   [created] => [2013-10-10 00:00:00];
            )
        )
    )
)

我想要类似的东西:

array(
    [Service] => array(
        (int) 0 => array(
                [id] => [1]
                [name] => [dropbox]
        )
    )

有任何想法吗?。

4

1 回答 1

3

您应该使用可包含的行为。它易于使用,您可以根据需要获取数据。

 $plateFormuser = $this->Platformuser->find('first', array(
     'conditions' => array('Platformuser.id' => $userId),
     'contain' => array(
         'Service' => array(
             'fields' => array('id', 'name') 
         )
      )
    ));

 $services = Set::merge(
        Set::classicExtract($plateFormuser, 'Service.{n}.{id}'),
        Set::classicExtract($plateFormuser, 'Semester.{n}.{name}')
 );

现在您可以对 $services 进行 json 编码以获取您提到的结果[{"id":"1", "name":"dropbox"}]

于 2013-10-10T16:01:51.760 回答