2013-04-29 94 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