2010-05-28 99 views
0

我在CakePhp上的模型上找到find()时遇到了一些麻烦。CakePhp:模型递归关联和查找

我有三个模型,以这种方式relationed:

项目(some_fields,ITEM_ID) ------属于关联----->项目(some_fields,ITEM_ID) ------ belongsTo -----> User(some_fields campi,昵称)

我需要做一个find()并检索项目中的所有字段,Item中的字段和User中的昵称字段。这是我的代码:

$this->set('projects', $this->Project->find('all', array('recursive' => 2))); 

但我的输出不包含用户对象。 我试着用可容忍的行为,但输出是相同的。什么坏了?

非常非常感谢

彼得

+3

除非你在这里有一个拼写错误,你似乎没有'items'表中的'user_id'字段。 – Mike 2010-05-28 13:47:46

+0

您可以发布您的可容纳数组(代码)还是您已应用于模型字段的可容纳提取中的条件? – 2010-05-28 16:12:50

回答

1

你的方法产生太多的疑问。您可能希望通过绑定和解除绑定模型来减少数量。看详情here

1

正确设置你的模型或尝试加入

$this->Project->recursive = -1; 
$this->Project->find('all', array(
    'joins'=>array(
     array(
     'table'=>'item', 
     'alias'=>'Item', 
     'type'=>'INNER', 
     'conditions'=>array(
      'Item.id=Project.item_id' 
      ) 
     ), 
     array(
     'table'=>'user', 
     'alias'=>'User', 
     'type'=>'INNER', 
     'conditions'=>array(
      'User.id=Item.user_id' 
     ) 
    ) 
    ), 
    'fields'=>array(
    //necessary 
    ), 
    'conditions'=>array(
    //if any 
    ); 
1

Project.php型号文件应如下

<?php 
App::uses('AppModel','Model'); 
/* 
* 
* Project Model 
* 
*/ 
Class Project extends AppModel{ 

/* 
* 
* actsAs Behaviour 
* 
*/ 
    public $actsAs = array('Containable'); 

/* 
* 
* belongsTO association 
* 
*/ 
    public $belongsTo = array(
     'Item' => array(
      'className' => 'Item', 
      'foreignKey' => 'project_id', 
      ) 
     ); 
} 
?> 

Item.php型号文件应如下

<?php 
App::uses('AppModel','Model'); 
/* 
* 
* Item Model 
* 
*/ 
Class Item extends AppModel{ 

/* 
* 
* actsAs Behaviour 
* 
*/ 
    public $actsAs = array('Containable'); 

/* 
* 
* belongsTO association 
* 
*/ 
    public $belongsTo = array(
     'User' => array(
      'className' => 'User', 
      'foreignKey' => 'item_id', 
      ) 
     ); 
/* 
* 
* hasMany association 
* 
*/ 
    public $hasMany = array(
     'Project' => array(
      'className' => 'Project', 
      'foreignKey' => 'project_id', 
      ) 
     ); 
} 
?> 

User.php型号文件应该如下

<?php 
App::uses('AppModel','Model'); 
/* 
* 
* User Model 
* 
*/ 
Class User extends AppModel{ 

/* 
* 
* actsAs Behaviour 
* 
*/ 
    public $actsAs = array('Containable'); 


/* 
* 
* hasMany association 
* 
*/ 
    public $hasMany = array(
     'Item' => array(
      'className' => 'Item', 
      'foreignKey' => 'item_id', 
      ) 
     ); 
} 
?> 

您可以尝试在控制器中使用下面的代码。

<?php 
$contain = array('Item' => array('User')); 
$this->set('projects', $this->Project->find('all', array('contain' => $contain))); 
?>