使用Propel和Backbone的多行toJSON函数

时间:2013-04-08 20:44:39

标签: php json orm propel slim

我正在尝试使用Propel ORM制作一个非常简单的“全部列出”功能 - 用于Backbone.js阅读。这就是我想要做的事情,在我看来,应该有用:

$users = UsersQuery::create()
->find();

echo $users->toJSON();

然而,当我正在运行时,我得到的结果是:

{"Users_0":{"Id":1,"EmailAddress":"sdf","Password":"sdf","CreatedAt":null,"ModifiedAt":null},
"Users_1":{"Id":2,"EmailAddress":"dsf","Password":"sdf","CreatedAt":null,"ModifiedAt":null}}

虽然它是有效的JSON,但是在主数组中,row是一个数组的事实是抛弃我的JSON。我需要它返回的是这样的JSON:

[{"Id":1,"EmailAddress":"sdf","Password":"sdf","CreatedAt":null,"ModifiedAt":null},{"Id":2,"EmailAddress":"dsf","Password":"sdf","CreatedAt":null,"ModifiedAt":null}]

我已经创建了下面的函数(作为测试)并且它完美地工作,但是肯定Propel(或Slim,我正在使用的框架)有办法阻止一切都在数组中?黑客;

$users = UsersQuery::create()
->find();

$json = '[';
foreach($users as $user){
    $json = $json.$user->exportTo('JSON').',';
}
$json = $json.']';
echo str_replace("},]", "}]", $json);

任何帮助将不胜感激!谢谢大家。

3 个答案:

答案 0 :(得分:1)

我不想这么说,但我认为这只是其中一个“那就是Propel的工作方式”。也就是说,你可以稍微提高你的辅助功能,使其更加健壮。

我会把这段代码放在你的UserQuery类中:

class UsersQuery extends BaseUsersQuery {
  ...

  public function toJSONArray() {
    $users = $this->find();
    $userArray = array();
    foreach($users as $user){
      array_push($userArray, $user->toArray());
    }
    return json_encode($userArray);
  }
}

然后像这样使用它......

$userJSON = UsersQuery::create()->toJSONArray();

或者,如果您有其他标准......

$userJSON = UsersQuery::create()
              ->filterBySomeField("someValue")
              // other Criteria ...
              ->toJSONArray();

答案 1 :(得分:0)

是否有可能在一个语句中使用this和select过滤器的解决方案。像这样:

   $ojson = TblproductQuery::create()
        ->select(array('ProdtID', 'DivnID'))
        ->toJsonArray();

答案 2 :(得分:0)

接受的答案没有解决的一件事是你有一个嵌套集合的对象。就像你可能有一堆测试一样有这样的答案:

[
  {
    id:test1,
    answers : [
      { id: 1, answer: pig},
      { id: 2, answer: dog}
    ]
  },
  {
    id:test2,
    answers : [
      { id: 5, answer: duck},
      { id: 6, answer: swan}
    ]
  }
]

当您尝试使用已接受的答案时,上述内容将无法与骨干集合很好地协作。这是因为每个推进模型都会在其自身的任何推进集合上调用PropelCollection::toArray()方法

PopelCollection::toArray()方法只会将自身作为关联数组返回给php,它会转换为JSON中的未排序集而不是数组。骨干集合仅对(数组)进行排序。

要解决此问题,我只是将推进源文件toArray()中的PropelCollection.php方法更改为以下内容:

public function toArray(
    $keyColumn = null, 
    $usePrefix = false, 
    $keyType = BasePeer::TYPE_PHPNAME, 
    $includeLazyLoadColumns = true, 
    $alreadyDumpedObjects = array()){

  $ret = array();
  foreach ($this as $key => $obj) {
    array_push($ret, $obj->toArray($keyType, $includeLazyLoadColumns, 
      $alreadyDumpedObjects, true);
  }

  return $ret;
}

我还没有看到它如何影响toXML或toYAML方法,但它允许toJSON方法按照我想要的方式使用嵌套集合,如上例所示。