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

Monday, February 21, 2022

[FIXED] How to order a CakePHP query by an aggregate function on an associated table's field?

 February 21, 2022     cakephp, cakephp-3.0, query-builder     No comments   

Issue

I want to order by an aggregate function on an associated table's field, but when I debug the SQL query being executed, the associated table, PersonaHistory doesn't even get JOINed, and of course I don't get any results.
Is there a way to achieve this?
Can I force a table to be joined in the query?

$query = $this->Personas->find('all')
    ->contain(['PersonaHistory'])
    ->order(['MAX(PersonaHistory.updated)' => 'ASC'])
    ->group('PersonaHistory.persona_id');  

DB: Personas has many PersonaHistory


Solution

It looks as if Personas is related to PersonaHistory via hasMany. Only hasOne and belongsTo associations produce a JOIN statement.

A workaround is to rewrite your query as:

$query = $this->PersonaHistory->find('all')
    ->contain(['Personas'])
    ->order(['MAX(PersonaHistory.updated)' => 'ASC'])
    ->group('PersonaHistory.persona_id');  


Answered By - Inigo Flores
  • 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