Walter Vos
Walter Vos

Reputation: 575

How to pass conditions to "contain" in get() call?

When getting a single record, and associated records (two levels down), is there any way we can pass condition to the contained records in CakePHP 3? In this case, for example:

$user = $this->Users->get($this->Auth->user('id'), [
    'contain' => [
        'Articles' => ['Comments']
    ]
]);

If tried a bunch of ways with callbacks, but that only seems to work on the first level. Like so, for example:

$user = $this->Users->get($this->Auth->user('id'), [
    'contain' => [
        'Articles' => function ($q) {
            return $q->where(['Articles.published' => true]);
        }
    ]
]);

Any thoughts?

Upvotes: 1

Views: 1031

Answers (2)

Greg Schmidt
Greg Schmidt

Reputation: 5099

@arilia's options should work fine. My preference is

$user = $this->Users->get($this->Auth->user('id'), [
    'contain' => [
        'Articles' => [
            'queryBuilder' => function ($q) {
                return $q->where(['Articles.published' => true]);
            },
            'Comments' => [
                'querybuilder' => function ($q) {
                    return $q->where(['Comments.deleted' => false]);
                }
            ],
        ],
    ],
]);

(Tried to post this as a comment, instead of a separate answer, but it won't format the code properly there.)

Upvotes: 0

arilia
arilia

Reputation: 9398

you should be able to do:

$user = $this->Users->get($this->Auth->user('id'), [
     'contain' => [
        'Articles' => function ($q) {
            return $q->where(['Articles.published' => true]);
        },
        'Articles.Comments' => function ($q) {
            return $q->where(['Comments.deleted' => false]);
        }
    ]
]);

or

$user = $this->Users->get($this->Auth->user('id'), [
     'contain' => [
        'Articles' => function ($q) {
            $q->contain([
                 'Comments' => function ($q) {
                    return $q->where(['Comments.deleted' => false]);
                }
            ]);
            return $q->where(['Articles.published' => true]);
        }            
    ]
]);

Upvotes: 3

Related Questions