Matt Backslash
Matt Backslash

Reputation: 804

CakePHP find() conditions for association entries

I have following command, getting me entries from my DB with associated hasMany entries:

$teasers = $this->Teaser->find('all', array(
    'conditions' => array(
        'Teaser.published' => 1
    ),
));

Now also the posts entries will be fetched, due the hasMany relation.

The output looks like this:

array(
    0 => array(
        'Teaser' => array(
            'id' => '1',
            'user_id' => '63',
            'token' => '56d455bc20cfb56d455bc20d08',
            // this goes on
        ),
        'Post' => array(
            0 => array(
                'id' => '1',
                'teaser_id' => '1',
                'title' => 'blabla',
                'text' => 'blabla',
                'published' => 1,
                // this goes on
            )
        )
    )
)

Now my question is, how can I include something in the conditions, to filter also the Post-entries?

When I enter it like this, I get an error:

$teasers = $this->Teaser->find('all', array(
    'conditions' => array(
        'Teaser.published' => 1,
        'Post.published' => 1
    )
));

Upvotes: 0

Views: 248

Answers (3)

drmonkeyninja
drmonkeyninja

Reputation: 8540

The reason you're getting an error is that your relationship is a hasMany so when Cake does the contain it is actually doing more than one query for your find. As a result you can't specify 'Post.published' => 1 in the conditions as the Post alias won't exist in the primary query (the one retrieving your teasers).

Instead you need to pass the extra condition as part of the contain:-

$teasers = $this->Teaser->find('all', [
    'contain' => [
        'Post' => [
            'conditions' => [
                'Post.published' => 1
            ]
        ]
    ],
    'conditions' => [
        'Teaser.published' => 1,
    ]
]);

This will let Cake know the conditions you want to use when building the query for the posts.

Upvotes: 1

floriank
floriank

Reputation: 25698

You should read the documentation for containable and retrieving data. These are basics.

$teasers = $this->Teaser->find('all', array(
    'contain' => [
        'Post' => [
            'conditions' => [
                'published' => 1
            ]
        ]
    ],
    'conditions' => array(
        'Teaser.published' => 1,
    )
));

Upvotes: 1

Pradeep Singh
Pradeep Singh

Reputation: 1290

You can write condition in your model Teaser.php like

public $hasMany = array(
    'Post' => array(
        'className' => 'Post',
        'conditions' => array('Post.published' => 1)
    )
);

Upvotes: 0

Related Questions