【问题标题】:Serializing full php object with Propel使用 Propel 序列化完整的 php 对象
【发布时间】:2013-09-02 22:18:56
【问题描述】:

我在将两个查询的结果合并到一个 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)
    }
  }

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

【问题讨论】:

    标签: php json serialization propel


    【解决方案1】:

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

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

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

    或者重写toArray方法

    【讨论】:

      【解决方案2】:

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

      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());
      }
      

      【讨论】:

        猜你喜欢
        • 2019-06-01
        • 2011-08-19
        • 1970-01-01
        • 2012-04-15
        • 2018-01-09
        • 1970-01-01
        • 1970-01-01
        • 2013-02-12
        • 1970-01-01
        相关资源
        最近更新 更多