Skip to content

HasManyThrough Relations

vlucas edited this page Sep 22, 2012 · 2 revisions

Here's an example of HasManyThrough:

Situation

Chat rooms have user presence - a list of users currently in the chat room. I want to get loaded User entity objects for all the users currently in the chat room. This allows me to display a list of users in the chat room in the sidebar when users enter the room.

Tables

  • rooms
  • room_users
  • users

Code I want to use

$room->users for a collection of all the users in the room

Code for the Relation (HasManyThrough on Room Entity):

    public static function relations()
    {
        return array(
            // Active users in current room
            'users' => array(
                'type' => 'HasManyThrough',
                'entity' => 'Module\User\Entity',
                'where' => array('id' => ':throughEntity.user_id'),
                'throughEntity' => 'Module\Room\Users\Entity',
                'throughWhere' => array('room_id' => ':entity.id')
                )
        );
    }

Explanation

The result Entity we want is Module\User\Entity where the id equals the room_user.user_id column. We get this by going through the Module\Room\Users\Entity, using the current loaded room id matching to room_users.room_id.

I am using this exact code and scenario in Kikuchat.