-->

Adding custom columns to Propel model?

2019-04-12 04:24发布

问题:

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.