Best way to add relations to resultset

Hello!

I have a number of groups of items I want to retrieve using AJAX (foreign key to the user owning the groups). This works perfectly:

    public function loadGroupsAction() {
        header("Content-Type: application/json; charset=utf-8");

        $data = array();
        $user = User::loadUserFromSession($this->session);
        if($user instanceof User) {
            $groups = $user->getGroup(array("order" => "id asc"));
            $data["groups"] = $groups->toArray();
        }

        $this->exitSuccessfully($data);
    }

Now, the problem is that in the front end requesting the AJAX, I also want to show the number of items each group contains. This is also solved with keys and relations set up in the model, but when I do $user->getGroups(), I obviously get a resultset, which I can't add data to. The only solution I see right now is either creating a specialized query instead, or looping over each resultset item and adding it to a separate array which I then relay back in the response, but both of these solutions are really poor.

Which would be the best way of retrieving the user's Groups, then including the count of the Items from the groups?

Hope I made sense .___.

Thanks for an awesome framework.

// dimhoLt

You can use new phacon model event: afterFetch(), this is not described in DOC, but you can find it on this forum. http://forum.phalconphp.com/discussion/388/how-to-get-all-event-types-do-phalcon-has-onload-event-

In your case you can do something like this:

in model User:

public function afterFetch()
{
    $this->user_groups = Groups::find("user_id=".$this->user_id)->toArray(); //try to cache this in production
}

in your code you have user goups under $user->user_groups property.



15.4k

THANK YOU! I was wondering why there were only update / save events.