2015-03-31 20 views
1

我正在使用CakePHP,我不知道如何連接兩個表中的數據。從其他表中獲取用戶名author_id CakePHP

這是我的表中的數據

  1. 用戶

ID,用戶名,密碼 - 等

  • 消息
  • 編號,標題,文本,作者

    現在我有控制器,其中我有作用,這得到最新消息,從表新聞

    $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

    使用加盟涉及這些表: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); 
    
    +1

    感謝您的幫助!這就像一個魅力:D! – GamaPL 2015-04-01 10:42:51