Search code examples
phpcodeignitercodeigniter-2phpactiverecord

PHP-activerecord - relation has_many (users, groups, users_groups)


I want to do this on my view but it´s not working:

<?php echo $user->group->name;?>

I have 3 tables

- users (id, name)
- groups (id, name)
- users_groups (id, user_id, group_id)

I have 2 models

class User extends ActiveRecord\Model
{
    static $belongs_to = array(
        array('group', 'through' => 'users_groups')
    );
}

class Group extends ActiveRecord\Model
{
    static $has_many = array(
        array('users' , 'through' => 'users_groups')
    );
}

My models are wrong or miss something? I need another model users_groups? If is yes, how would be called?

I need help, i don´t find the correct way.

Thanks!


Solution

  • The solution is:

    class User extends ActiveRecord\Model
    {
        static $has_many = array(
        array('groups', 'through' => 'usersgroups', 'order'=>'id asc'),
            array('usersgroups')
        );
    }
    
    
    class Group extends ActiveRecord\Model 
    {
        static $has_many = array(
            array('users' , 'through' => 'usersgroups'),
            array('usersgroups')
        );
    }
    
    class UsersGroup extends ActiveRecord\Model
    {
        static $table_name = 'users_groups';
    
        static $belongs_to = array(
            array('user'),
            array('group')
        );
    }
    

    The problem was with the name of the of third model (UsersGroup in singular)