Adding custom columns to Propel model?

混江龙づ霸主 提交于 2019-12-06 09:26:23

问题


At the moment I am using the below query:

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

However I then want to add columns manually, so I thought this would simply work:

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

However when the data is returned Propel or Symfony2 seems to be stripping the custom data when it gets converted to JSON along with all of the superflous model data.

What is the correct way of manually adding data this way?


回答1:


To export virtual columns to out array you can do it the next way:

/**
 * 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:


The answer to this lies in the toArray() method so:

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

Then you can modify as required, the only issue here is that the current toArray method does not return virtual columns so you would have to patch the method to include them. (This is in the PropelObjectCollection class)

In the end I decided to separate the parts:

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

This way you do not have to worry about the virtual columns being lost and jut have to manipulate your data in different ways on the other end.



来源:https://stackoverflow.com/questions/13838465/adding-custom-columns-to-propel-model

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!