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.

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",
)));


7.7k
Accepted
answer
edited Jun '15

Never mind,

https://forum.phalconphp.com/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;
    }