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.
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.
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 :
/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:
To fill a select element containing categories, supposing you have a User belongsTo Category relationship :
$categories = $this->User->Category->find('list'); $this->set(compact('categories'));
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));