PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Tuesday, February 22, 2022

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

 February 22, 2022     cakephp, cakephp-3.0, orm     No comments   

Issue

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?


Solution

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]);
        }            
    ]
]);


Answered By - arilia
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing