控制器中的方法
public function getLike() {
$this->Feed->UserLikeFeed->recursive = 1;
$this->Paginator->settings = array(
'contain' => array('UserLikeFeed','UserCommentFeed','UserShareFeed')
);
$like_comment_shares = $this->Paginator->paginate();
$this->set(array(
'like_comment_shares' => $like_comment_shares,
'_serialize' => array('like_comment_shares')
));
}
模型
public $hasMany = array(
'Image' => array(
'className' => 'Image',
'foreignKey' => 'feed_id',
'dependent' => false,
'conditions' => '',
'fields' => '',
'order' => '',
'limit' => '',
'offset' => '',
'exclusive' => '',
'finderQuery' => '',
'counterQuery' => ''
),
'UserCommentFeed' => array(
'className' => 'UserCommentFeed',
'foreignKey' => 'feed_id',
'dependent' => false,
'conditions' => '',
'fields' => '',
'order' => '',
'limit' => '',
'offset' => '',
'exclusive' => '',
'finderQuery' => '',
'counterQuery' => ''
),
'UserLikeFeed' => array(
'className' => 'UserLikeFeed',
'foreignKey' => 'feed_id',
'dependent' => false,
'conditions' => '',
'fields' => '',
'order' => '',
'limit' => '',
'offset' => '',
'exclusive' => '',
'finderQuery' => '',
'counterQuery' => ''
),
'UserShareFeed' => array(
'className' => 'UserShareFeed',
'foreignKey' => 'feed_id',
'dependent' => false,
'conditions' => '',
'fields' => '',
'order' => '',
'limit' => '',
'offset' => '',
'exclusive' => '',
'finderQuery' => '',
'counterQuery' => ''
),
);
当我在控制器中访问该方法时,它返回的值如下图所示。我想获得一些数据。例如:UserLikeFeed,它返回两个值。我想得到2.我现在该怎么办?谢谢你的帮助。
结果
{
"like_comment_shares": [
{
"Feed": {
"id": "72",
"admin_id": "2",
"title": "New term",
"description": "This is a new term"
},
"UserCommentFeed": [
{
"user_id": "1",
"feed_id": "72",
"created": null,
"description": "Going home"
},
{
"user_id": "1",
"feed_id": "72",
"created": null,
"description": "Going School"
}
],
"UserLikeFeed": [
{
"user_id": "1",
"feed_id": "72"
},
{
"user_id": "2",
"feed_id": "72"
}
],
"UserShareFeed": [
]
},
答案 0 :(得分:0)
因为您正在对数据进行分页,所以您只能根据分页限制获取该特定页面的值,而不是考虑计算json结果,只需在将序列化为JSON之前计算数组中的结果,基本上就是可以做类似的事情:
$userlikefeed_count = count($like_comment_shares['UserLikeFeed']);
这将返回该数组中的项目数,然后您也可以将此数据发送到控制器:
$this->set(array(
'like_comment_shares' => $like_comment_shares,
'userlikefeed_count' => $userlikefeed_count
'_serialize' => array('like_comment_shares', 'userlikefeed_count')
));