Adding custom columns to Propel model?

余生长醉 提交于 2019-12-04 13:05:52

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

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.

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