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

Tuesday, February 22, 2022

[FIXED] CakePHP 3: Retrieving deep associations

 February 22, 2022     cakephp-3.0     No comments   

Issue

My model has

Conversations - hasMany - Messages

Conversations - hasMany - ConversationsRecipients

ConversationsRecipients - belongTo - Users or Applicants (depending on the flag set by field recipient_type. If recipient_type is A then it means Applicants)

So when I try to retrieve conversations for a particular Applicant, I use the following code

$conversationsTable = TableRegistry::get('Conversations');
        $conversations = $conversationsTable->find()
            ->join([
                'ConversationsRecipients' => [
                    'table' => 'conversations_recipients',
                    'type' => 'inner',
                    'conditions' => ['recipient_id' => $id, 'recipient_type' => 'A']
                ]
            ])
            ->contain([
                'Messages.Users' => function ($q) {
                    return $q
                        ->select(['Users.username'])
                        ->contain(['UsersProfiles']);
                },
                'Messages.Applicants' => function($q) {
                    return $q
                        ->select(['Applicants.firstname', 'Applicants.lastname']);
                }
            ])
            ->all();
        return $conversations;

This works fine - except for one part - but it doesn't retrieve the deeply contained model - UsersProfiles. Am I missing something?


Solution

Try this:

return $q
    ->select(['Users.username'])
    ->autoFields(true)
    ->contain(['UsersProfiles']);

When you include a select in your query, that's all that Cake will include, unless you include the autoFields call.



Answered By - Greg Schmidt
  • 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