【问题标题】:CakePHP Containable showing wrong dataCakePHP Containable 显示错误数据
【发布时间】:2012-10-02 23:54:12
【问题描述】:

我一直在寻找有关 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. 检索包含中提到的字段

我得到了什么

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

例子:

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

但让我们更进一步:

  1. 如果设置了 $recursive = -1,那么我只会返回模型“会计”的字段;未检索到 Instruction、Student、Teacher 字段

让我们确定

  • 我把“public $actsAs = array('Containable');”在所有其他模型继承的 AppModel 中
  • 是的,指令有一个“$belongsTo = array('Teacher', 'Student' => array(...))”
  • 加入所需的字段都被选中

那么,什么?

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

我已经试过了

  • 显式设置连接:很奇怪,然后 [Instruction][teacher_id] 为空且 [Instruction][Teacher] 未设置!
  • 省略要检索的字段的显式选择

【问题讨论】:

  • 你试过没有字段的包含吗?就像$this->find('all',array('contain'=>array('Instruction'=>array('Student','Teacher'))).. 它应该返回所有相关的学生和老师的指令。如果没有,你就会知道你的模型之间的关系有问题
  • 是的,我试过了。很奇怪:它返回所有数据,但现在只在设置正确的情况下显示教师(即如果教师满足条件),否则不设置 [Instruction][Teacher]。我怎样才能在条件为真的情况下返回指令?看起来它是左连接而不是内连接

标签: cakephp cakephp-2.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。

希望对你有帮助

【讨论】:

  • 感谢您在这种情况下澄清过滤器的含义 - 我不清楚。你的例子有效。但是,我现在遇到的一个问题是我得到了很多带有空指令的会计,因为过滤现在发生在更高的级别(但不幸的是不是在最高级别)。
  • 是的..这就是我认为它会做的XD..你将不得不手动进行连接Accounting JOIN Instruction ... JOIN Teacher ... JOIN Student ... WHERE Instruction.teacher_id =
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-09-14
  • 2016-05-10
  • 1970-01-01
  • 2011-12-19
  • 2011-12-29
相关资源
最近更新 更多