1

我在将两个查询的结果组合成一个 json 对象时遇到问题。

$item_results = ItemQuery::create('item')

    ->filterByCategory($categoryObjects, Criteria::IN)

    ->groupBy('item.ID')

    ->find();

返回一个像

{"ID":35,"Title":"Individual Asset","Description":"Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.","DateRecorded":"01\/02\/01"}

然后我想将类别重新附加,所以我运行

    foreach($item_results as $item_result) {

        $categories = ItemCategoryQuery::create()
            ->filterByItem($item_result)
            ->find();
        $item_result->categories = Array();
        $item_result->categories = $categories->toArray();
        echo json_encode($item_result->toArray());

    }

但是我在没有类别的情况下将其取回....相同的json。所以我跑了

    var_dump($item_result);

然后回来了

object(Item)#39 (18) {
  ["id":protected]=>
  int(35)
  ["title":protected]=>
  string(16) "Individual Asset"
  ["description":protected]=>
  string(124) "Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua."
  ["date_recorded":protected]=>
  string(10) "2001-01-02"
...
 ["categories"]=>
  array(2) {
    [0]=>
    array(2) {
      ["ItemID"]=>
      int(35)
      ["CategoryID"]=>
      int(19)
    }
    [1]=>
    array(2) {
      ["ItemID"]=>
      int(35)
      ["CategoryID"]=>
      int(15)
    }
  }

所以类别在新对象中,它只是不序列化......有什么想法吗?

4

2 回答 2

1

toArray() 是 Propel 生成的方法,它将对象的所有受保护值转换为数组。它从您的模型 - 模式中获取数组的键。

如果要生成不存在字段的数组,可以手动将此值分配给数组

$result = $item_result->toArray();
$result['categories'] = $categories->toArray()

或者重写 toArray 方法

于 2013-09-05T10:52:00.223 回答
0

我知道这是一个非常古老的问题,但我是否通过谷歌搜索找到了它,我认为写一个答案可能是值得的。

正如已经向您建议的那样,Propel 在它生成的每个模型上公开 toArray 方法,但该方法将仅处理模式定义中定义的属性或集合(下一个更多内容)。

您要实现的是模型实例(来自 ItemQuery::find 方法结果数组的元素)的序列化,其中包含相关的类别集合。

Propel 将基于关系的查询的结果存储到一个集合中,该集合是已进行查询的实例的受保护属性。如果某个关系的集合已从数据库中加载,则将包含在 toArray 方法的结果中。

在 Propel 模型中,关系的填充/检索方法以表格形式生成get + related_model_name_pluralized(如果关系是 1:N)。

我认为一个例子可能比文字更有帮助。

foreach($item_results as $item_result) {
    $item_result->getItemCategories(); //This is the method that will
                                       //populate the collection.
    //Now the collection is populated so we can json_encode
    echo json_encode($item_result->toArray());
}
于 2016-05-06T12:50:59.703 回答