我正在尝试将最新用户的id从UsersController发送到AdminController,其add_employee()操作会创建一个新员工。我的用户和员工表是分开的,我想要做的是当管理员创建新用户时,其条目进入用户表。然后,他打开创建员工表单,最新的用户ID将分配给管理员创建的新员工。因此,当管理员打开创建新员工表单时,最新的用户ID将显示在表单中。 我的UsersController有这个代码,用于将最新用户发送到AdminsController:
public function get_latest_user_id()
{
$content = $this->User->query("SELECT id FROM users ORDER BY id DESC LIMIT 0,1");
$this->set('latest_user', $content);
}
AdminsController页面的add_employee包含以下代码:
public function add_employee()
{
$this->loadModel('Employee');
$this->set('latest_user', $this->requestAction('/Users/get_latest_user_id'));
if ($this->request->is('post'))
{
$this->Employee->create();
if ($this->Employee->save($this->request->data))
{
$this->Session->setFlash(__('The employee profile has been saved.'));
return $this->redirect(array('action' => 'list_of_employees'));
}
else
{
$this->Session->setFlash(__('The employee profile could not be saved. Please, try again.'));
}
}
}
因此,UserController的get_latest_user_id函数将最新的用户ID发送到AdminController的add_employee函数。有latest_user被设置为最新的用户ID,因此当调用add_employee视图时,它就在那里。但它没有表现出来。所以我想知道我做得对吗?请帮助和谢谢。
在add_employee.ctp中,我显示如下:
echo $latest_user['User']['id'];
答案 0 :(得分:0)
将get_latest_user_id
移至User model
public function get_latest_user_id()
{
$user = $this->query("SELECT id FROM users ORDER BY id DESC LIMIT 1");
if (empty($user)) {
return 0;
}
// return only the Id
return $user[0]['users']['id'];
}
在控制器中:
public function add_employee()
{
$this->loadModel('Employee');
$this->loadModel('User');
$this->set('latest_user', $this->User->get_latest_user_id());
if ($this->request->is('post'))
{
// ....
}
}
答案 1 :(得分:0)
cornelb是正确的,您应该将方法移动到您的用户模型。虽然更多的Cake-ish方法是使用find('first'),而不是直接query()
:
// app/Model/User.php
public function getLatest() {
// Get the latest user
$user = $this->find('first', array(
'fields' => array('id'), // Only interested in id? Use this.
'order' => array('User.id' => 'DESC')
));
if (!empty($user)) {
return $user['User']['id'];
} else {
// Nothing was returned, this is very awkward
throw new NotFoundException(__('No users found!'));
}
}
在你的控制器中:
// app/Controller/AdminsController.php
public function add_employee() {
$this->loadModel('User');
$this->set('latestUser', $this->User->getLatest());
// ...
}