2013-04-29 99 views
0

我有這些表:使用多個型號查找()CakePHP的

表:CREATORS

**CREATORS**

obs.:I've也試過這樣:

enter image description here

表格:POSTS

enter image description here

CreatorModel.php

class CreatorModel extends AppModel { 
    public $actsAs = array('Containable'); 
    public $hasOne = array('Post'); 
} 

PostModel.php

class PostModel extends AppModel { 
    public $actsAs = array('Containable'); 
    public $hasOne = array('Creator'); 
} 

IndexController.php

$this->set('posts', $this->Post->find()); 

index.ctp

var_dump($posts); 

繼CakeBook會議關於協會 http://book.cakephp.org/2.0/en/models/associations-linking-models-together.html

我應該接受觀點的迴應:

Array 
(
    [Post] => Array 
     (
      [id] => 1 
      [creator_id] => 1 
      [tags] => 
      [title] => Teste 
      [post] => Maromba 
      [created] => 2013-04-29 19:14:32 
      [modified] => 2013-04-29 19:14:32 

     ) 
    [Creator] => Array 
     (
      [creator_id] => 1 
      [creator] => Alexandre Moraes 
     ) 
) 

但我收到此:

Array 
(
    [Post] => Array 
     (
      [id] => 1 
      [creator_id] => 1 
      [tags] => 
      [title] => Teste 
      [post] => Maromba 
      [created] => 2013-04-29 19:14:32 
      [modified] => 2013-04-29 19:14:32 

     ) 
) 

那麼,任何想法我做錯了什麼?

+0

你需要閱讀cakephp文檔並遵循約定(這很容易)http://book.cakephp.org/2.0/en/models/associations-linking-models-together.html – Nunser 2013-04-29 18:27:16

+0

在db中,更改'creator_id' for'id' in the table'creators' – Nunser 2013-04-29 19:16:39

+0

@nuns,仍然是相同的迴應...沒有「創建者」鍵 – Alexandre 2013-04-29 19:18:58

回答

2

在db

CREATORS TABLE 
--- 
id | creator 

Creator.php

class Creator extends AppModel { 
    public $actsAs = array('Containable'); 
    public $hasOne = array('Post'); 
} 

帖子。PHP

class Post extends AppModel { 
    public $actsAs = array('Containable'); 
    public $belongsTo= array('Creator'); 
} 

請注意模型的命名和post.php中的關聯類型

IndexController.php

$this->set('posts', $this->Post->find('all', array('contain'=>array('Creator'))); 

做這些改動之後,返回數組應該是你期待的一個。

+0

作出這些更改...仍然不工作... :( – Alexandre 2013-04-29 19:36:17

+0

也更改模型文件的名稱(在我的答案中更改它) – Nunser 2013-04-29 20:03:20

+0

感謝@nuns,該作品 – Alexandre 2013-04-29 20:16:20

0

您需要爲您的模型設置正確的關係。你基本上希望在兩個表之間進行連接。看看這個答案:https://stackoverflow.com/a/5080026/2297744我相信它和你想要做的很相似。

的快速和骯髒的版本將是這個樣子:

$this->Post->find('all', array(
    'joins' => array(
     array(
      'table' => 'creators', 
      'alias' => 'CreatorJoin', 
      'type' => 'inner', 
      'conditions' => array(
       'CreatorJoin.id = Post.creator' 
      ) 
     ) 
    ) 
); 

但我建議你閱讀完整的答案,我掛,並使用第一(更正確)的例子。

+0

我已經編輯了我的問題,顯示了我擁有下面的CakeBook。即使你發送的鏈接,我無法得到這個工作。任何想法? – Alexandre 2013-04-29 19:15:55