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

Conditions from other model

Hello, I've got a problem. I have two models, Month and TimesheetMonth. I would like to choose with help of TimesheetMonth::findFirst() but with Month conditions (values year and month). Is there any built in function, or I should use SQL builder instead

How are the two models connected?

Assuming TimesheetMonth uses the foreign key:

month_id

the you would be able to connect the two models with hasMany and belongsTo:

https://docs.phalcon.io/en/latest/reference/models.html

Month

<?php

namespace Admin\Models;

use \Phalcon\Mvc\Model;

class Month extends Model
{

    public $id;
    public $year;
    public $month;
    public $work_days;
    public $optymalize_days;

    public function hasMany($fi, $rt, $rf, $op = array())
    {
        parent::hasMany($fi, "\\" . __NAMESPACE__ . "\\" . $rt, $rf, $op);
    }

    public function initialize()
    {
        $this->hasMany('id', 'TimesheetMonth', 'month_id', array('alias' => 'TSM'));
    }

}

TimesheetMonth

<?php

namespace Admin\Models;

use \Phalcon\Mvc\Model;

class TimesheetMonth extends Model
{

    public $id;
    public $month_id;
    public $user_id;
    public $hour_to_work;
    public $hour_work;
    public $hourly;
    public $overtime;
    public $overtime_multiplier;

    public function hasMany($fi, $rt, $rf, $op = array())
    {
        parent::hasMany($fi, "\\" . __NAMESPACE__ . "\\" . $rt, $rf, $op);
    }

    public function belongsTo($fi, $rt, $rf, $op = array())
    {
        parent::belongsTo($fi, "\\" . __NAMESPACE__ . "\\" . $rt, $rf, $op);
    }

    public function initialize()
    {
        $this->hasMany('id', 'Timesheet', 'tsm_id', array('alias' => 'timesheet'));
        $this->belongsTo('month_id', 'Month', 'id', array('alias' => 'month'));
    }

}

And I would like to get record timesheetMonth, which belongs to user "user_id=1" for year=2014 and month=11. Is there an option to do that after the download of only 1 record, or I have to chose an exact record from Month, and after that a record from TimesheetMonth

As far as I know, you either have to load in a month record, and then get the corresponding timsheetMonth record, or, use a query.