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

Is it possible to set default ordering while finding related records?

Is it possible to set default ordering while finding related records for a particular record by alias (through magic __get)?

<?php
class Robots extends \Phalcon\Mvc\Model
{
    public function initialize()
    {
        $this->hasMany('id', 'RobotsParts', 'robot_id', ['alias' => 'parts']);
    }
}

class RobotsParts extends \Phalcon\Mvc\Model
{
    public function initialize()
    {
        $this->belongsTo('robot_id', 'Robots', 'id', ['alias' => 'robot']);
    }
}

$robot = Robots::findFirst();
$robot->parts; // unordered RobotsParts here

I can use $robot->getParts(['order'=>'name']) but it will execute new DB query for every call, while access through property will execute query only ones.



98.9k

Actually both ways execute a second query:

$robot->parts
and
$robot->getParts(['order'=>'name'])


29.4k

@Phalcon are you sure?

I've just tested it: $robot->parts executes SQL query only ones $robot->getParts() executes query for every call (the same query)

Check yourself https://gist.github.com/Agent-J/c4e1a3afa9998ec13277