【问题标题】:How do I add conditions for related (belongsTo) Model in CakePHP 1.3?如何在 CakePHP 1.3 中为相关 (belongsTo) 模型添加条件?
【发布时间】:2010-12-08 16:24:55
【问题描述】:

我见过类似的问题,但他们的答案似乎对我不起作用。这似乎应该很简单,所以我觉得问起来很愚蠢。

我有一个名为 Preappform 的模型,它有许多代理模型(对于 Preappform 有 belongsTo)。代理模型有一个包含哈希的字段。当我检索 Preappform 时,它会自动返回任何通过适当外键关联的代理,但我想限制此代理列表仅包含其 Agent.hash 字段与提供的条件匹配的代理。

这是当前代码:

models/agent.php

class Agent extends AppModel {
    var $name = "Agent"; // Singular for instances. 
    var $belongsTo = array('Preappform');
}

models/preappform.php

class Preappform extends AppModel {
    var $name = "Preappform";
    var $hasMany = array('Agent'); 
    /* snip, some validation stuff */
}

在控制器中……(仿照别人的例子)

// $id = 18
// $hash is set to false, or a nonexistent value. 

$the_form = $this->Preappform->find('first', 
    array(
        'conditions' => array('Preappform.id' => $id), 
        'contain' => array('Agent' => array('conditions' => array('Agent.hash' => $hash))) 
    )    
); 

结果:

阵列 ( [Preappform] => 数组 ( [id] => 18 [创建] => 2010-12-03 08:56:12 [修改] => 2010-12-03 08:56:12 [完成] => 0 /* ... */ ) [代理] => 数组 ( [0] => 数组 ( [id] => 1 [preappform_id] => 18 [哈希] => f312d4b401fecc8ce0f8dca6eb7c1ca6ad9f5956 ) [1] => 数组 ( [id] => 2 [preappform_id] => 18 [哈希] => f312d4b401fecc8ce0f8dca6eb7c1ca6ad9f5957 ) ) )

我在 Preappform 模型上玩弄了各种版本的“包含”和“递归”的不同值,但似乎无法过滤可用的代理。

我认为它会像

一样简单
$the_form = $this->Preappform->find(
    'first', 
    array('conditions' => array(
        'Preappform.id'=> $id, 
        'Agent.hash' => $hash
        ) 
    )
);

...但这总是给出“未知列:代理...”错误。

如何应用条件来过滤通过我的 Preappform 模型返回的代理?

【问题讨论】:

    标签: php cakephp cakephp-1.3


    【解决方案1】:

    在模型中

    models/preappform.php // add this
    var $actsAs = array('Containable');
    

    在控制器中

    models/preappform.php
    $the_form = $this->Preappform->find(
        'first', 
        array(
             'conditions' => array('Preappform.id' => $id) ,
             'contain' => array('Agent' => array('conditions' => array('Agent.hash'=>$hash)))
        )
    );
    

    【讨论】:

    • 我在代理模型中添加了“可包含的行为”,并更改了控制器中的相应行,但我仍在接收 所有 相关代理。 =/
    • 这在我将 $actsAs 放置在父 (Preappform) 模型中时有效,但当它放置在子 (Agent) 模型中时。这可能是我的错误配置吗?
    【解决方案2】:

    类似于the answer by Ish Kumar,但有一个更正:

    Preappform(父)模型应该“充当可包含”。

    当我将以下行添加到 Preappform 模型时:

    var $actsAs = array('Containable');

    ...以下代码中的“包含”条件开始按预期工作:

    $the_form = $this->Preappform->find('first', 
        array(
            'conditions' => array('Preappform.id' => $id), 
            'contain' => array('Agent' => array('conditions' => array('Agent.hash =' => $hash))) 
        )
    ); 
    

    谢谢!

    【讨论】:

      【解决方案3】:

      我相信您可以执行以下操作: array('contain' => 'Agent.hash = "'.$hash .'"')

      【讨论】:

      • 这并没有改变我的结果。仍然得到两个代理。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-09-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多