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?



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

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

how can I get catalog sort by poem liked?

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