We have moved our forum to GitHub Discussions. For questions about Phalcon v3/v4/v5 you can visit here and for Phalcon v6 here.

MAX in relationship

Hi again!

I've try to have max() on a field from a relation. I explain, i've got a hasMany relation and i need to get the max from a field. Here is an exemple :

Model A hasMany Model B. Model B has a position field. I can easily get related with A->getAliasRelation(); and add parameters but is there an easy way to get related model with only the row with max position ?

I'm not sure to be very clear because of my english, so tell me if i made any mistake!

In Phalcons current form I don't think this would be possible to do with one PHQL query (due to the lack of subquery support), nor one action against the ORM.

If you wanted to do raw SQL, you could do it one query with a subquery, but if you'd prefer to use Phalcon and if you are okay with 2 separate SQL queries, you could do something like this.

if($max = ModelA::maximum(['column' => 'position'])){
    ModelA::findFirstByPosition($max->position);
}