문제

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!

도움이 되었습니까?

해결책

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)

다른 팁

class User extends ActiveRecord\Model
{
    function get_group($user_id){
        $query = "SELECT name FROM groups 
                  LEFT JOIN users_groups ON (groups.id=users_groups.group_id)
                  LEFT JOIN users ON (users_groups.user_id=users.id)";
        $this->group = mysql_fetch_object($query);
    }
}

add this function to your User function

I think the answer to your question is in the manual. This is an example of many-to-many association, that you are trying to implement. In this case groups is orders and users_groups is payments.

enter image description here

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

 class Payment extends ActiveRecord\Model {
   static $belongs_to = array(
     array('user'),
     array('order')
   );
 }

 class User extends ActiveRecord\Model {
   static $has_many = array(
    array('payments')
   );
 }

 $order = Order::first();
 # direct access to users
 print_r($order->users); # will print an array of User object
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top