Взаимосвязь между моделью в cakephp

#cakephp-2.0

#cakephp-2,0 #cakephp-2.0

Вопрос:

У меня есть две таблицы user (id, email, имя пользователя, пароль) и post (id, user_id, заголовок, тело), у меня много связей в обеих моделях, теперь, когда я добавляю post, он показывает идентификатор пользователя в действии добавления, все работает нормально, но я хочу видеть имя пользователя вместо user_id в действии добавления post. как это сделать? это моя почтовая модель:

 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' => ''
    )
);
  

}

это моя функция добавления постконтроллера:

  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'));
}
  

Ответ №1:

Попробуйте это:

 $users = $this->Post->User->find('list', array('fields' => array('User.username')));
  

Ответ №2:

попробуйте обновить свой запрос, укажите свои поля:

    $users = $this->Post->User->find('list', 
                                     array("fields" =>array(
                                                       "User.id",
                                                        "User.email"
                                                      )
                                          )
                                     );