Dmitriy Smirnov
Dmitriy Smirnov

Reputation: 449

CakePHP: Find across multiple models

I have several models that all share one fields (say name) but differ in other fields. Is there any wan to find all of ModelX ModelY and ModelZ that have name 'foo'. Thanks for any suggestions.

Upvotes: 2

Views: 2083

Answers (2)

Tom
Tom

Reputation: 591

If the they are related you should be able to specify the Model followed by '.' within the find.

    $this->find('all', array(
        'conditions' => array(
             'OR' => array(
                  'Article.field' => 'foo',
                  'Comment.field' => 'foo',
                  'Post.field' => 'foo',
              )
         ),
        'fields' => array('Article.field', 'Comment.field', 'Post.field')
    ));

Upvotes: 2

G.J
G.J

Reputation: 795

Something like this ?

$models = array('Post', 'Comment', 'Article');
$results = array();

foreach($models as $model) {
    $this->loadModel($model);
    $results[$model] = $this->{$model}->find('all', array(
        'conditions' => array(
            $model'.name' => $name
        )
    ));
}

Upvotes: 3

Related Questions