views:

315

answers:

3

Hi i have table "User" and a Controller "users_controller.php" and i have another table called "cateogry", need to retrieve values from this table in the "listall" action(site.com/users/listall).

how can i get values from another table.

A: 

I guess you have a hasMany relation between your User and Category models ?

Then it's deadly easy.

$this->User->find('first')->Category->find('all');

Will retrieve every category associated with the user.

Some resources that might be helpful to you :

Damien MATHIEU
i need to fill some values from "cat" table to a "select" element in the registration. suppose for the signup page list all the countries form the country table
coderex
`->find('first')->Category` seems odd, don't you just mean `User->Category` ?
deceze
A: 

/models/user.php:

var $actsAs = array('Containable');
var $hasMany = array('Category');

/controllers/users_controller.php:

function listall()
{
    $users = $this->User->find('all', array('contain' => array('Category')));
    $this->set('users', $users);
}

/views/users/listall.ctp:

foreach($users as $user)
{
    echo htmlspecialchars($user['User']['username']);
    echo '<ul>';
    foreach($user['User']['Category'] as $category)
    {
        echo '<li>';
        echo htmlspecialchars($category['description']);
        echo '</li>';
    }
    echo '</ul>';
}

use the debug function to reveal the $users array:

debug($users);

Check out the documentation on containable behaviour:

http://book.cakephp.org/view/474/Containable

GJ
+1  A: 

To fill a select element containing categories, supposing you have a User belongsTo Category relationship :

  • in the controller, get the categories ready to be used in a select element
$categories = $this->User->Category->find('list');
$this->set(compact('categories'));
  • in the view add your select element :
echo $form->input('User.category_id');

Cake will automatically use the values contained in the $categories variable for the category_id select thanks to the Inflector. If for some reason your values are in a different variable, use

echo $form->input('User.category_id', array('options' => $values_array));
Matthieu Sadouni