CakePHP-2.0 How can i get the username from $allposts=$this->paginate('Post'); where user_id is foreign key of posts table?

喜欢而已 提交于 2019-12-12 04:35:45

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!