We are moving our forum in GitHub Discussions. For questions about Phalcon v3/v4 you can visit here and for Phalcon v5 here.

Solved thread

This post is marked as solved. If you think the information contained on this thread must be part of the official documentation, please contribute submitting a pull request to its repository.

How to order by count of related model?

I have a model Poem, which hasMany PoemLike.

class Poem extends \Phalcon\Mvc\Model
{
    /**
     * Define relationships to PoemLike
     */
    public function initialize()
    {
        $this->hasMany('id', 'PoemLike', 'poem_id', array(
            'alias' => 'likes',
        ));
    }
}

I want find top 10 poems with most likes, How could I do this?



98.9k
Accepted
answer
$poems = $this->modelsManager->createBuilder()
    ->colums('Poem.id', 'number' => 'COUNT(*)')
    ->from('Poem')
    ->join('PoemLike')
    ->orderBy('number')
    ->groupBy('Poem.id');
    ->getQuery()
    ->execute();


5.2k

Hi, Let's say that every Poem has on catalog,

how can I get catalog sort by poem liked?

$poems = $this->modelsManager->createBuilder()
  ->colums('Poem.id', 'number' => 'COUNT(*)')
   ->from('Poem')
   ->join('PoemLike')
   ->orderBy('number')
  ->groupBy('Poem.id');
   ->getQuery()
   ->execute();