0

我在 CakePhp 上的模型上的 find() 遇到了一些麻烦。

我以这种方式关联了三个模型:

Project(some_fields, item_id) ------belongsTo-----> Item(some_fields, item_id) ------belongsTo-----> User(some_fields campi, 昵称)

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

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

但我的输出不包含用户对象。我已经尝试过 Containable 行为,但输出是相同的。什么坏了?

非常感谢

彼得

4

3 回答 3

1

Project.php Model file should be as below

<?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 Model file should be as below

<?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 Model file should be as below

<?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',
            )
        );  
}
?>

You can try with below code in the controller.

<?php
$contain = array('Item' => array('User'));
$this->set('projects', $this->Project->find('all', array('contain' => $contain)));
?>
于 2014-06-04T05:37:37.720 回答
1

您的方法会生成太多查询。您可能希望通过绑定和解除绑定模型来减少它们的数量。在此处查看详细信息。

于 2010-05-28T19:22:36.200 回答
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
   );
于 2014-05-30T11:11:28.307 回答