CakePHP包含显示错误数据

时间:2012-10-12 07:43:12

标签: cakephp cakephp-2.0

我一直在寻找可以容纳CakePHP的很长一段时间,不知怎的,我得到的印象是CakePHP代码中有一个错误...让我给你以下例子

假设与“指令”相关的模型“会计”。

public $belongsTo = array('Instruction');

我像这样加入:

$options['contain'] = array(
        'Instruction' => array(
           'fields'  => array('Instruction.id', 'Instruction.main_student_id', 'Instruction.teacher_id'),
           'Student' => array(
               'fields' => array('Student.id', 'Student.full_name', 'Student.invoice_payer_id'),
           ),
           'Teacher' => array(
                'fields' => array('Teacher.id', 'Teacher.full_name'),
                'conditions' => array('Teacher.id' => $teacher_id)
           ),
        )
);      
return parent::find('all', $options);

所以有一个指导和一个学生和一个老师属于这个指令。我从“会计”模型中调用了find

我的期望

  1. 联接自动完成并正确
  2. 检索包含中提到的字段
  3. 我得到了什么

    1. 字段已加入,但错误;所以结果数组包含一个学生和教师的指令。但是,它不是显示属于指令的正确教师,而是始终显示条件中指定的教师。
    2. 示例:

      • 假设与教师相关的表格“1 - John Appleseed”,“2 - Peter Googleseed”,“3 Larry Microseed”
      • 假设属于3位教师的多条指令
      • 如果$ teacher_id = 3,则查询返回所有指令,而不是显示属于指令的正确教师,而是显示id = 3的教师;更确切地说:[指令] [teacher_id]设置为正确的值,但[指令] [教师]始终设置为条件的教师

      但让我们更进一步:

      1. 如果设置了$ recursive = -1,那么我只返回模型“Accounting”的字段;教学,学生,教师的领域未被检索
      2. 让我们确定

        • 我把“public $ actsAs = array('Containable');”在AppModel中,所有其他模型继承
        • 是的,说明有“$ belongsTo =数组('老师','学生'=>数组(...))”
        • 选择加入所需的字段

        那么,什么?

        请你帮我理解......   - 为什么连接错误地完成?   - 为什么不检索所有字段?

        我已经尝试了

        • 明确设置联接:非常奇怪,然后[指令] [teacher_id]为空,[指令] [教师]未设置!
        • 省略明确选择要检索的字段

1 个答案:

答案 0 :(得分:1)

Containable also goes a step deeper: you can filter the data of the associated models.

http://book.cakephp.org/2.0/en/core-libraries/behaviors/containable.html#containing-deeper-associations

您对可包含项的条件用作过滤器,而不是对连接的限制。因此,它不会返回某位教师的说明,而是返回所有说明及其相关教师,以条件array('Teacher.id' => $teacher_id)

过滤教师

尝试在教学中添加条件而不是教师。类似的东西:

'Instruction' => array(
    'Student','Teacher',
    'conditions' => array('Instruction.teacher_id' => $teacher_id)

这将返回所有会计,它只会过滤某位老师的指示。

你总是可以手动进行连接(它看起来不太好但是有效),如果你这样做,只记得将containsable设置为false。

希望这有帮助