我正在使用beforeSave()
为用户分配一个临时客户编号。我需要将此值返回给访问API的设备。是否可以从我的控制器访问它?
// app/Model/User.php
<?php
class User extends AppModel {
function beforeSave($options) {
$this->data['User']['customerNumber'] = uniqid(); // This is the value I want
$this->data['User']['password'] = md5($this->data['User']['password']);
}
function isUnique() {
$users = $this->find('all', array('conditions' => array('email' => $this->data['User']['email'])));
if (empty($users)) {
return true;
} else {
return false;
}
}
}
?>
// app/Controller/UserController.php
<?php
class UserController extends AppController {
public $components = array('RequestHandler');
public function register() {
if ($this->request->is('post')) {
$this->User->set($this->data);
if ($this->User->isUnique()) {
if ($this->User->save($this->data)) {
// This is where I need to return the customer number
echo json_encode(array('status' => 'User registered', 'customerNumber' => $this->data['customerNumber']));
} else {
echo json_encode(array('status' => 'User could not be registered'));
}
} else {
echo json_encode(array('status' => 'user is duplicate'));
}
} else {
echo json_encode(array('error' => 'Requests must be made using HTTP POST'));
}
}
}
?>
作为次要问题,uniqid()
是否可以分配临时客户号码?
答案 0 :(得分:1)
您无法直接获得该值,但您可以在成功保存后立即获取该值,例如:
if ($this->User->save($this->data)) {
// Fetch inserted row
$user = $this->User->findById($this->User->getInsertId());
echo json_encode(array(
'status' => 'User registered',
'customerNumber' => $user['User']['customerNumber']
));
}