Reputation: 5230
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!
Upvotes: 0
Views: 4190
Reputation: 5230
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)
Upvotes: 3
Reputation: 2346
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.
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
Upvotes: 0
Reputation: 748
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
Upvotes: 0