我想在我看来这样做,但它不起作用:
<?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?如果是,那怎么称呼?
我需要帮助,我找不到正确的方法。
谢谢!
答案 0 :(得分: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')
);
}
问题在于第三个模型的名称(UsersGroup in singular)
答案 1 :(得分: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);
}
}
将此功能添加到您的用户功能
答案 2 :(得分:0)
我认为你问题的答案在manual。这是您尝试实现的多对多关联的示例。在这种情况下,组是订单,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