简体   繁体   English

PHP-activerecord - 关系has_many(users,groups,users_groups)

[英]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 我有3张桌子

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

I have 2 models 我有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')
    );
}

My models are wrong or miss something? 我的模特错了或错过了什么? I need another model users_groups? 我需要另一个模型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) 问题在于第三个模型的名称(UsersGroup以单数形式)

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. 在这种情况下,组是订单,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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM