doufeixi6014 2012-10-17 15:58
浏览 20
已采纳

CakePHP查询和JSON输出 - 改进当前的解决方案

I'm coding a tagging system in CakePHP (latest release) but the solution I have made seems over complicated compared to how easy the rest of CakePHP is. Hopefully someone can point me in the right direction or help me improve my current solution.

I need to pass to my view data in this format (JSON):

[{label:'actionscript', count: 14}, {label:'php', count: 2} ... ]

Now I know the following SQL query gives me the needed data:

SELECT tags.name, count(*)
FROM tags
RIGHT JOIN tags_users
ON tags.id=tags_users.tag_id
GROUP BY name";

So using CakePHP find method I made:

$options = array();
$options['contain'] = '';   
$options['recursive'] =  -1;            
$options['joins'][0]['table'] = 'tags_users';
$options['joins'][0]['type'] = 'RIGHT';
$options['joins'][0]['conditions'] = 'Tag.id = tags_users.tag_id';
$options['fields'] =  array('name', 'COUNT(*) as tag_counter');
$options['group']  =  'Tag.name';
$options['order']  =  'tag_counter DESC';       
$availableTagsArray = $this->User->TagsUser->Tag->find('all', $options);

This give me an array out as:

Array
(
[0] => Array
    (
        [Tag] => Array
            (
                [name] => actionscript
            )

        [0] => Array
            (
                [tag_counter] => 14
            )

    )

[1] => Array
    (
        [Tag] => Array
            (
                [name] => php
            )

        [0] => Array
            (
                [tag_counter] => 2
            )

    )
)

I then convert this array to JSON by:

$availableTags = "[";

foreach ($availableTagsArray as $tag) {
        $availableTags .= "{label:'{$tag['Tag']['name']}', count:{$tag[0]['tag_counter']}},";   
    }

$availableTags = substr($availableTags, 0, -1);
$availableTags .= "]";  
$this->set("availableTags", $availableTags);

[UPDATE]

After doing a lot of research and using both answers. I've found there multiple ways to do this and that includes my original solution. You could also use virtual fields then the afterFind method and flattening the results there.

  • 写回答

2条回答 默认 最新

  • douyinghuo8874 2012-10-17 16:04
    关注

    You can use the Containable Behavior to simplify your query and a JSON view to simplify your output.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 公交车和无人机协同运输
  • ¥15 stm32代码移植没反应
  • ¥15 matlab基于pde算法图像修复,为什么只能对示例图像有效
  • ¥100 连续两帧图像高速减法
  • ¥15 如何绘制动力学系统的相图
  • ¥15 对接wps接口实现获取元数据
  • ¥20 给自己本科IT专业毕业的妹m找个实习工作
  • ¥15 用友U8:向一个无法连接的网络尝试了一个套接字操作,如何解决?
  • ¥30 我的代码按理说完成了模型的搭建、训练、验证测试等工作(标签-网络|关键词-变化检测)
  • ¥50 mac mini外接显示器 画质字体模糊