<?php class Controller_Activity extends Controller_Application { public function action_index() { $friends = array(); foreach ($this->current_user->friends as $f) { $friends[] = $f->friend_id; } $this->data['activities'] = Model_Activity::find() ->where('user_id', 'IN', $friends) ->order_by('created_at', 'desc') ->get(); $this->template->title = 'Activity'; $this->template->content = View::forge('activity/index', $this->data); } }
$friends = array(); $result = Model_Friends::query()->select('friend_id')->where('user_id', '=', $this->current_user->id)->get(); foreach ($result as $f) { $friends[] = $f->friend_id; }which results in a slightly more optimal query.
Harro Verton wrote on Wednesday 3rd of October 2012:What I mean with eager loading is that when you ran the query to fetch $this->current_user, if you have included "->related('friends')" (or the same in array notation), a join is executed to fetch both the current_user and prepopulate the friends objects. If not, then the ORM will fire a "SELECT *" query as soon as you access a friends object, which means a second query. Only in this case a slight improvement is possible, because in terms of efficiency nothing beats retrieving the data using a join.
$this->current_user = Model_User::find($user_id);
It looks like you're new here. If you want to get involved, click one of these buttons!