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

How to use join on getRelated()

I am trying to getRelated rows while having join that is required by the WHERE condition. In other words I would like to fetch answers of the session on questions which have not been deleted.

Sessions have multiple questions and answers.

This is what I'd like to do. Obviously this doesn't work. Whats the best way to achieve this?

$this is Session model

$this->getRelated('MyApp\Models\Answers', array( "conditions" => "questions.deleted = 0", "join" => "questions" ) );

getRelated returns a hydrated object list, so there is no way to attach columns from a joined table.

You should use ORM, in your model's initialize set up a 1-N relationshop between answers and questions.

class Answer extends Phalcon\Mvc\Model
{
    public function initialize()
    {
        $this->belongsTo('question_id', 'MyApp\Models\Question', 'id', ['alias'=>'Question']);
    }
}
class Question extends Phalcon\Mvc\Model
{
    public function initialize()
    {
        $this->hasMany('id', 'MyApp\Models\Answer', 'question_id', ['alias'=>'Answers']);
    }
}
class SomeController extends Phalcon\Mvc\Controller
{
    public function indexAction()
    {
        $answer = Answer::findFirst();
        $title = $answer->Question->getTitle(); // or whatever field you want to access
    }
}

Use query builder.