只有一個查詢我有兩種型號:CakePHP的 - 從外部型號
class Post extends AppModel {
var $name = 'Post';
var $belongsTo = array(
'User' => array(
'className' => 'User',
'foreignKey' => 'user_id'
)
);
}
和
class User extends AppModel {
var $name = 'User';
var $hasMany = 'Post';
}
現在我一個具有與PostsController
查詢的問題。我有一個add()
函數和視圖add.ctp這基本上是一種形式。現在我想以這種形式顯示一些用戶信息。
class PostsController extends AppController {
var $name = 'Posts';
var $helper = array('Html', 'Form');
var $uses = array('User');
public function index() {
$this->set('posts', $this->Post->find('all'));
}
function add() {
$user_id = 1;
$this->set('user', $this->User->findById($user_id));
if ($this->request->is('post')) {
if ($this->Post->save($this->request->data)) {
$this->Session->setFlash('Your post has been saved.');
$this->redirect(array('action' => 'index'));
} else {
$this->Session->setFlash('Unable to add your post.');
}
}
}
}
但是現在,add-view-page顯示實際上兩個查詢在哪裏觸發。所以,如果我print_r($user)
內添加視圖我得到一個數組與兩個數組。一個用於郵政與USER_ID = 1,一個ID爲實際的用戶= 1。但是我想只得到用戶ID = 1
我找不到var'$ user' – 2012-04-01 21:48:54
您想在哪裏獲得ID爲1的用戶?在'PostsController :: add()'? – 2012-04-01 21:49:43
對不起,'$ user'是來自視圖,我是對的? – 2012-04-01 21:50:35