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

Wednesday, January 5, 2022

[FIXED] Cakephp 3 dynamically build contain

 January 05, 2022     cakephp, cakephp-3.0, eager     No comments   

Issue

How can I dynamically build the contain in the new cakephp 3 query builder. This is what I have now:

$query = $dbTable->find()
                ->select($contain['select']['fields'])
                ->contain(function($q) use($array,$contain){
                      $new = [];
                      foreach($array as $v){
                        if(isset($contain['contains'][$v])){
                          $fields = $contain['contains'][$v];
                          $new[$v] = $q->select($fields);
                         }
                      }
                      return $new;
                  });

But I am getting several errors with this:

Warning (2): Illegal offset type in isset or empty [CORE\src\ORM\EagerLoader.php, line 198]
Warning (2): strpos() expects parameter 1 to be string, object given [CORE\src\ORM\EagerLoader.php, line 203]
Warning (2): Illegal offset type [CORE\src\ORM\EagerLoader.php, line 223]
Warning (2): Illegal offset type [CORE\src\ORM\EagerLoader.php, line 224]

Solution

As already mentioned by Lorenzo, that's not how it works, contain() doesn't accept callables, just look at the docs:

http://api.cakephp.org/3.0/class-Cake.ORM.Query.html#_contain

Also your code would invoke select() multiple times on one and the same query, that wouldn't work anyways.

However, looking at your code it seems that you could simply make use of the fields option, ie build a simple array to pass to contain(). This is shown in the docs, the example however will trigger an error as it seems to be necessary to explicitly set the foreign key field too:

$query->contain([
    'Articles' => [
        'fields' => ['foreign_key_column_name', 'title']
    ]
]);


Answered By - ndm
  • 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