问题
I'm using CakeDC-Users plugin.
<?php
class Post extends AppModel {
public $useTable='posts';
public $belongsTo = array('User');
public $hasMany=array('Comment');
}
I had to use paginate:
$allposts=$this->paginate('Post');
I can get the user_id in this way:
foreach ($allposts as $post) {
debug($post['Post']['user_id']);
But i need the username not the user_id. How can i get username?
回答1:
The containble feature of CakPHP hides all associated models by default: http://book.cakephp.org/2.0/en/core-libraries/behaviors/containable.html
If you want to add only one field of an associated Model you can use this syntax:
$allposts = $this->Post->find('all', array('contain' => 'User.username'));
or with paginate use this in your controller class: (http://book.cakephp.org/1.3/en/view/1232/Controller-Setup)
var $paginate = array('contain' => 'User.username');
Try the following to access it:
$post['User']['username'];
回答2:
Try setting the recursive property to 2:
$this->Post->recursive = 2;
$allposts = $this->paginate('Post');
debug($allposts);
$allposts
should contain every Post and it's belonging user.
See also: Cakephp pagination on recursive conditions
来源:https://stackoverflow.com/questions/9872094/cakephp-2-0-how-can-i-get-the-username-from-allposts-this-paginatepost-w