从另一个表CakePHP获取author_id从其他表中获取用户名

时间:2015-03-31 22:43:36

标签: php mysql cakephp

我使用CakePHP而且我不知道如何连接两个表中的数据。

这是我的表数据

  1. 用户
  2. id,用户名,密码 - 等等

    1. 消息
    2. id,title,text,author

      现在我有控制器,我有行动从表新闻获取最新消息

      $this->set('n_news', $this->News->find('all', array('limit' => 10,'order' => array('News.id DESC'))));  
      

      现在我有一个看起来像这样的数组

      array(
      (int) 0 => array(
          'News' => array(
              'id' => '1',
              'title' => 'test',
              'text' => 'test #1',
              'author' => '1',
              'date' => '2014-09-25 22:56:55'
          )
      )
      

      现在我想显示作者的用户名(ID为1)而不是id。我怎样才能安全有效地做到这一点?

      如果有人能帮助我,那真是棒极了。这对我未来创建应用程序的计划有很大帮助:)

      提前致谢!

1 个答案:

答案 0 :(得分:1)

使用联接来关联这些表:JOIN TABLES

$joins = array(
                array(
                    'table' => 'users',
                    'alias' => 'User',
                    'type' => 'INNER',
                    'conditions' => array('News.auther = User.id'
                )
            );
$allnews = $this->News->find('all', array('fields'=>array('News.*','User.username as AutherName'),'joins' => $joins,'limit' => 10,'order' => array('News.id DESC')));

$this->set('n_news',$allnews);
相关问题