Search code examples
fuelphpfuelphp-orm

Fuel PHP - to_array() method and multiple belongs_to relationships and eager loading


I am attempting to migrate some legacy data models/schemas to a fuel API, and have run into an odd issue with the to_array() method on a model that has two $_belongs_to properties.

When I load the model without the to_array() method, I properly receive both related items with eager loading, but as soon as I pass them through this function to convert the data to make it digestable by the new API, it will strip out the second $_belongs_to property. If I re-order the props in the $belongs_to array, it will show whichever item is first in the array.

My question is, how can I convert this data to an array without losing the second relationship?

Here are some cleaned up examples for ease of reference:

Transaction Model:

protected static $_belongs_to = array(
    'benefactor' => array(
        'key_from' => 'from_user_id',
        'model_to' => 'Model\\Legacy\\User',
        'key_to' => 'id',
    ),
    'user' => array(
        'key_from' => 'user_id',
        'model_to' => 'Model\\Legacy\\User',
        'key_to' => 'id',
    ),
);

Transaction Controller:

$result = array();
$id = $this->param('id');

if (!empty($id)) {
    $transaction = Transaction::find($id, array('related' => array('user', 'benefactor',)));
    if (!empty($transaction)) {

        // Works -- both benefactor and user are returned
        $result['transaction_works'] = $transaction;

        // Does not work -- only the benefactor is returned
        $result['transaction_doesnt_work'] = $transaction->to_array();
    }
}

return $this->response($result);

Solution

  • For any googlers looking for help on this issue, I was seemingly able to return all relationships by simply executing the to_array() method before setting the return/results variable:

    $result = array();
    $id = $this->param('id');
    
    if (!empty($id)) {
         $transaction = Transaction::find($id, array('related' => array('user', 'benefactor',)));
        if (!empty($transaction)) {
            $transaction->to_array();
            $result['transaction_works'] = $transaction;
        }
    }
    
    return $this->response($result);
    

    Good luck!