NDeveloper
NDeveloper

Reputation: 41

CakePHP Group get user information

How can I get the group information about my users..?
In my table users I have a row group_id (id = 1)
This id is linked to my table groups. (id 1 = group admin)

So what I want is when a user logged in example, Welcome User || You are Admin.

I've trying to do this, but it doesn't work. Does anybody know what's wrong?

$group = $this->User->Group->findById($id); 

    $users = $this->User->find('all', array(
        'conditions' => array(
            'User.group_id' => $id
        )
    ));

    echo $group;

Many Thanks !

Upvotes: 1

Views: 1232

Answers (2)

Tim
Tim

Reputation: 5943

Easy. And it's not even necessary to use the containable behavior, as long as the user group is on the first level of association. It's important that you have all your associations set within your models

user.php (Model)
var $belongsTo = array('Group');

group.php (Model)
var $hasMany = array('User');

Assuming you know the id of your user all you have to do is this:

users_controller.php
$user = $this->User->read(null, $id);

This will give you an array from which you can access the associated group like this:

$user['Group']['name']; //or whatever key you use for the term "Admin"

Upvotes: 2

Gevious
Gevious

Reputation: 3252

use the containable behaviour

It looks like you're trying to find all the users in a group. Turn the query around:

$users = $this->User->find('first',array(
    'conditions'=>array('User.id'=>$id),
    'contain'=>array('Group')
));

collect your data from $users['Group']

Upvotes: -1

Related Questions