How do I add conditions for related (belongsTo) Model in CakePHP 1.3?
I have seen similar questions, but their answers don't seem to be working for me. This seems like it should be really straightforward, so I feel pretty stupid for asking.
I have a model called Preappform that hasMany Agent models (which have belongsTo for Preappform). The Agent model has a field containing a hash. When I retrieve a Preappform, it automatically gives me back any Agents that are related by the appropriate foreign key, but I'd like to limit this list of Agents to contain only those whose Agent.hash field matches a supplied condition.
Here's the current code:
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 */
}
In the controller... (following the example of others)
// $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)))
)
);
The result:
Arrray ( [Preappform] => Array ( [id] => 18 [created] => 2010-12-03 08:56:12 [modified] => 2010-12-03 08:56:12 [completed] => 0 /* ... */ ) [Agent] => Array ( [0] => Array ( [id] => 1 [preappform_id] => 18 [hash] => f312d4b401fecc8ce0f8dca6eb7c1ca6ad9f5956 ) [1] => Array ( [id] => 2 [preappform_id] => 18 [hash] => f312d4b401fecc8ce0f8dca6eb7c1ca6ad9f5957 ) ) )
I've toyed with various versions of "contains" 开发者_运维知识库and different values for "recursive" on the Preappform Model, but can't seem the filter the available Agents.
I thought it would be as simple as
$the_form = $this->Preappform->find(
'first',
array('conditions' => array(
'Preappform.id'=> $id,
'Agent.hash' => $hash
)
)
);
... but that always gives an "Unknown column: Agent..." error.
How can I apply conditions to filter the Agents returned with my Preappform model?
In Model
models/preappform.php // add this
var $actsAs = array('Containable');
In Controller
models/preappform.php
$the_form = $this->Preappform->find(
'first',
array(
'conditions' => array('Preappform.id' => $id) ,
'contain' => array('Agent' => array('conditions' => array('Agent.hash'=>$hash)))
)
);
Similar to the answer by Ish Kumar, but with a correction:
The Preappform (parent) Model should "act as Containable".
When I added the following line to the Preappform model:
var $actsAs = array('Containable');
... the 'contain' conditions in the following code started working as expected:
$the_form = $this->Preappform->find('first',
array(
'conditions' => array('Preappform.id' => $id),
'contain' => array('Agent' => array('conditions' => array('Agent.hash =' => $hash)))
)
);
Thanks!
I believe you can do something like:
array('contain' => 'Agent.hash = "'.$hash .'"')
精彩评论