0

我想按照我的观点这样做,但它不起作用:

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

我有 3 张桌子

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

我有 2 个模型

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')
    );
}

我的模型是错误的还是遗漏了什么?我需要另一个模型 users_groups?如果是,怎么称呼?

我需要帮助,我找不到正确的方法。

谢谢!

4

3 回答 3

2

解决方案是:

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')
    );
}

问题在于第三个模型的名称(单数用户组)

于 2012-06-25T11:04:47.480 回答
0
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);
    }
}

将此功能添加到您的用户功能

于 2012-06-25T07:48:59.057 回答
0

我认为您的问题的答案在手册中。这是您尝试实现的多对多关联的示例。在这种情况下,groups 是订单,users_groups 是付款。

在此处输入图像描述

 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
于 2012-06-25T09:12:12.253 回答