【问题标题】:CakePHP-2.0 How can i get the username from $allposts=$this->paginate('Post'); where user_id is foreign key of posts table?CakePHP-2.0 如何从 $allposts=$this->paginate('Post'); 获取用户名user_id 是帖子表的外键在哪里?
【发布时间】:2012-03-26 12:27:01
【问题描述】:

我正在使用 CakeDC-Users 插件。

<?php
class Post extends AppModel { 
    public $useTable='posts';
    public $belongsTo = array('User');
    public $hasMany=array('Comment');
}

我不得不使用分页:

$allposts=$this-&gt;paginate('Post');

我可以通过这种方式获取user_id:

foreach ($allposts as $post) {
    debug($post['Post']['user_id']);

但我需要用户名而不是 user_id。如何获取用户名?

【问题讨论】:

  • 您遗漏了一些代码——尤其是您从模型中检索数据的代码!
  • 我听不懂你在说什么。你能详细说明一下吗?

标签: cakephp join inner-join cakephp-2.0 foreign-key-relationship


【解决方案1】:

CakPHP 的可包含特性默认隐藏所有关联模型:http://book.cakephp.org/2.0/en/core-libraries/behaviors/containable.html

如果您只想添加关联模型的一个字段,您可以使用以下语法:

$allposts = $this->Post->find('all', array('contain' => 'User.username'));

或者在你的控制器类中使用分页:(http://book.cakephp.org/1.3/en/view/1232/Controller-Setup)

var $paginate = array('contain' => 'User.username');

尝试以下方法来访问它:

$post['User']['username'];

【讨论】:

  • 不,我无法获得 ['username'] 它是 ['user_id'] ,我在帖子模型中有 public $actsAs = array('Containable');
  • 实际上我指的是关于“可包含”的部分,因为这会改变 find 的工作方式。
  • 它真的会帮助您阅读文档。您可以对分页使用与查找相同的参数。
  • 不是 cakephp-1.3 而是 cakephp-2.0。
  • 2.0 中的 Containable 没有任何变化
【解决方案2】:

尝试将递归属性设置为 2:

$this->Post->recursive = 2;
$allposts = $this->paginate('Post');
debug($allposts);

$allposts 应该包含每个帖子及其所属用户。

另请参阅:Cakephp pagination on recursive conditions

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-06-30
    • 1970-01-01
    • 2022-01-23
    • 1970-01-01
    • 1970-01-01
    • 2019-01-22
    • 1970-01-01
    • 2016-12-24
    相关资源
    最近更新 更多