2013-02-03 51 views
0

我试图拆分出一些JSON字符串以便通过此RestKit的iPhone库进行解析,但CakePHP正在拆分不兼容的字符串。例如,下面的字符串就是它目前分裂出来:更改CakePHP关联模型的方式

1. {"Question":{"id":"1","content":"Test","player_id":"1","points":"0","votes":"0","created":"0000-00-00 00:00:00"},"Player":{"id":"1","username":"player_test"}} 

我需要这样的:

2. {"Question":{"id":"1","content":"Test","player_id":"1","points":"0","votes":"0","created":"0000-00-00 00:00:00","Player":{"id":"1","username":"player_test"}}} 

注意的是,玩家的反应应该是问题的一部分。

的方式模型是蛋糕上的设置是'Question' belongs to 'Player'后者hasMany 'Question'

我找告诉蛋糕输出类似上面的响应#2的正确方法。有什么建议么?

回答

0

您可以使用afterFind()回答您的问题模型,以将播放器记录嵌套在问题记录中。或者在获取之后根据需要修改结果数组。 Hash类的各种功能可能会帮助您重新格式化数组。

+0

请谨慎操作。将代码添加到afterFind()回调将导致用该模型执行的所有查询的结果都被更改。这可能不是你想要的。我会发布替代 – thaJeztah

+0

你是对的。我应该可能在我的评论中添加了免责声明。 – ADmad

+0

没问题,afterFind()*可以*是做这件事的地方,只是为了防止经验较少的CakePHP用户搞砸他们的应用程序,因为他们不知道它在做什么:) – thaJeztah

0

您可以将自定义方法添加到您的问题模型中,并以所需的格式返回结果。这将保持您的代码清洁,并将数据处理/格式化逻辑保留在您的模型中(在大多数情况下应该是这种情况);

例如,你的问题模型中:

public function getQuestionsForPlayer($playerId) 
{ 
    $results = $this->find('all', array(
     'fields' => array(/* fields */), 
     'conditions' => array(/* ..... */ 
     /* etc */ 
    )); 

    // Process your result to be in the right format 
    // Hash::extract() and other Hash:: methods 
    // may be helpful here as @ADmad mentioned 

    return $processedResult; 
} 

正如ADmad提到,散列工具可能会有所帮助。文档位于此处:

http://book.cakephp.org/2.0/en/core-utility-libraries/hash.html