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

Saturday, January 1, 2022

[FIXED] How to contain unassociated entities in CakePHP?

 January 01, 2022     cakephp, cakephp-3.0, php     No comments   

Issue

Sample query:

TableRegistry::getTableLocator()
    ->get('Parents')
    ->find()
    ->contain([
        'Children' => function (Query $query) {
            return $query->where([
                'Children.code = Parent.code'
            ]);
        }
    ])

Parent and Children tables only have code as common field.

How do I define their association?

How do I contain unassociated entities?


Solution

You can customize the foreignKey and bindingKey in association configuration

In ParentsTable.php:

$this->hasMany('Children', [
    'bindingKey' => 'code',
    'foreignKey' => 'code'
]);

This config will set which fields to look for when associating entities.

Then you could associate entities on your controller like this:

// This query will contain children where Children.code === Parent.code
TableRegistry::getTableLocator()
    ->get('Parents')
    ->find()
    ->contain('Children');


Answered By - kgbph
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home
View mobile version

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