We have moved our forum to GitHub Discussions. For questions about Phalcon v3/v4/v5 you can visit here and for Phalcon v6 here.

Model relations - how to get a populated array

Hello! I have two models: Number and Order. Order has many Numbers, so Number belongs to Order.

I need to:

$numbers = Number::find();
...
echo json_encode($numbers);

I can use $number->order .. and it works fine. But how can I populate the array with all related data, so I can send it via JSON?

Thanks!



27.7k
Accepted
answer
$numbers = Number::find();
$result = [];
foreach($numbers as $n){
    $arr = $n->toArray();
    $arrOrder = ($n->order) ? $n->order->toArray() : null;
    $arr['order'] = $arrOrder;
    $result[] = $arr;
}

echo( json_encode($result));
edited Jun '15
class Number implements JsonSerializable
{
    public function jsonSerialize()
    {
        $ret = $this->toArray();
        $ret['order'] = ($this->order) ? $this->order->toArray() : null;
        return $ret;
    }
}

$numbers = Number::find()->filter(function($el){return $el;});
echo json_encode($numbers);