【问题标题】:Adding custom columns to Propel model?将自定义列添加到 Propel 模型?
【发布时间】:2012-11-30 01:56:19
【问题描述】:

目前我正在使用以下查询:

$claims = ClaimQuery::create('c')
        ->leftJoinUser()
        ->withColumn('CONCAT(User.Firstname, " ", User.Lastname)', 'name')
        ->withColumn('User.Email', 'email')
        ->filterByArray($conditions)
        ->paginate($page = $page, $maxPerPage = $top);

然后我想手动添加列,所以我认为这很简单:

foreach($claims as &$claim){
    $claim->actions = array('edit' => array(
            'url' => $this->get('router')->generate('hera_claims_edit'),
            'text' => 'Edit'    
            )
        );
    }

return array('claims' => $claims, 'count' => count($claims));

但是,当数据被返回时,Propel 或 Symfony2 似乎在将自定义数据与所有多余的模型数据一起转换为 JSON 时剥离。

以这种方式手动添加数据的正确方法是什么?

【问题讨论】:

    标签: php orm propel symfony-2.1


    【解决方案1】:

    要将虚拟列导出到数组中,您可以使用以下方式:

    /**
     * Propel result set
     * @var \PropelObjectCollection
     */
    $claims = ClaimQuery::create('c')-> ... ->getResults();
    
    /**
     * Array of data with virtual columns
     * @var array
     */
    $claims_array = array_map(function (Claim $claim) {
       return array_merge(
           $claim->toArray(), // using "native" export function
           array( // adding virtual columns
               'Email' => $claim->getVirtualColumn('email'),
               'Name' => $claim->getVirtualColumn('name')
           )
       );
    }, $claims->getArrayCopy()); // Getting array of `Claim` objects from `PropelObjectCollection`
    
    unset($claims); // unsetting unnecessary object if we have further operations to complete
    

    【讨论】:

      【解决方案2】:

      这个问题的答案在于 toArray() 方法,所以:

      $claims = ClaimQuery::create('c')
          ->leftJoinUser()
          ->withColumn('CONCAT(User.Firstname, " ", User.Lastname)', 'name')
          ->withColumn('User.Email', 'email')
          ->filterByArray($conditions)
          ->paginate($page = $page, $maxPerPage = $top)->getResults()->toArray();
      

      然后您可以根据需要进行修改,这里唯一的问题是当前的 toArray 方法不返回虚拟列,因此您必须修补方法以包含它们。 (这是在 PropelObjectCollection 类中)

      最后我决定把部分分开:

      return array(
              'claims' => $claims, 
              'count' => $claims->count(),
              'actions' => $this->actions()
          );
      

      这样您就不必担心虚拟列会丢失,而只需在另一端以不同的方式操作您的数据。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2013-08-04
        • 2021-04-21
        • 2023-03-21
        • 1970-01-01
        • 1970-01-01
        • 2013-08-02
        • 1970-01-01
        • 2014-04-02
        相关资源
        最近更新 更多