Solved thread

This post is marked as solved. If you think the information contained on this thread must be part of the official documentation, please contribute submitting a pull request to its repository.

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!



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