我有两个表用户(ID,电子邮件,用户名,密码)和帖子(id,user_id,title,body), 我在两个模型中有很多关系, 现在,当我添加帖子时,它在添加操作中显示用户ID,它可以正常工作,但我想在后添加操作中看到用户名而不是user_id。 怎么做? 这是我的帖子模型:
class Post extends AppModel {
public $useTable = 'post';
public $displayField = 'title';
public $validate = array(
'title' => array(
'notEmpty' => array(
'rule' => array('notEmpty'),
),
),
'body' => array(
'notEmpty' => array(
'rule' => array('notEmpty'),
),
),
);
public $belongsTo = array(
'User' => array(
'className' => 'User',
'foreignKey' => 'user_id',
'conditions' => '',
'fields' => '',
'order' => ''
)
);
}
这是我的postcontroller添加功能:
public function add() {
if ($this->request->is('post')) {
$this->Post->create();
if ($this->Post->save($this->request->data)) {
$this->Session->setFlash(__('The post has been saved.'));
return $this->redirect(array('action' => 'index'));
} else {
$this->Session->setFlash(__('The post could not be saved. Please, try again.'));
}
}
$users = $this->Post->User->find('list');
$this->set(compact('users'));
}
答案 0 :(得分:0)
尝试更新您的查询,指定您的字段:
$users = $this->Post->User->find('list',
array("fields" =>array(
"User.id",
"User.email"
)
)
);
答案 1 :(得分:0)
试试这个:
$users = $this->Post->User->find('list', array('fields' => array('User.username')));