我有以下关系:
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]
)
)
任何想法?。
答案 0 :(得分: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}')
);
现在你可以json编码$ services来获得结果,如你所提到的[{"id":"1", "name":"dropbox"}]
。