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

ORM - retriveing only selected related records.

Hey guys here is my situation. I would like only select a certain Has Many related records.

I have a model Users.

$this->hasMany('id', 'Nova\Models\Accounts', 'userId', array(
    'alias' => 'accounts',
    'foreignKey' => array(
        'message'=> 'This user still has accounts assigned to it'
)));

As you can see this user has many accounts.

The accounts Belong to the users.

$this->belongsTo("userId", "Nova\Models\Users", "id", array(
    'alias' => 'accountOwner'
));

On the accounts modle i have a datetime stamp.

I would like to only have a selected range of datetimes to be pulled in when i do a ::find like this. So that i can do some calculations on just those accounts in the range. I know that i could iterate over the objects and check each objects timesamp, but i would prefer to save as much cputime/memory as i can

 $users = Users::find(array(
    'conditions'=> 'rentCost > ?1 AND active = ?2',
    'bind' => array(
        1 => 0,
        2 => "Y",
)));


18.6k
Accepted
answer
edited Jun '15

Never mind,

https://forum.phalcon.io/discussion/2104/related-records-automatically-including

The solution on this worked great.

I added this to my account User Model

    public function getAccountsBetween($start, $stop){
        $accounts = Accounts::query()
            ->columns(array('sum(systemSize) as sumSystemSize'))
            ->betweenWhere('signDate',$start,$stop) 
            ->andWhere('userId = :userId:', array('userId'=>$this->id))  
            ->execute();
        return $accounts;
    }