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 are relations supposed to work on find() calls?

I'm working on a project where most of the queries are done through the QueryBuilder, what I find quite awful as the team is not quite used to the model relations and find the "find()" method way too basic for what we do. I'm trying to change this mind but it's getting quite hard. Here follows an example of what I'm trying to do, and I'm lost on what's going wrong:

//models/Things.php
class Things extends \Phalcon\Mvc\Model {

    public function initialize() {
        parent::initialize();
        $this->belongsTo('thing_type_id', ThingTypes::class, 'id', ['alias' => 'ThingTypes']);
        $this->belongsTo('thing_group_id', ThingGroups::class, 'id', ['alias' => 'ThingGroups']);
    }

}
//inside ThingEntity.php
$entries = Things::find([
    'conditions' =>
        'invoice_id IS NULL AND '.
        //'ThingGroups.User.UserTypes.name = :type: AND '. //<= extra-cool if this worked
        'ThingGroups.created_on <= :cut:',
    'bind' => [
        //'type' => $type,
        'cut'  => $cutDate
    ]
]);

That code throws me this:

Unknown model or alias 'ThingGroups' (11), when preparing: SELECT [PhalconRest\Models\Things].* FROM [PhalconRest\Models\Things] WHERE invoice_id IS NULL AND ThingGroups.created_on <= :cut: LIMIT :APL0: OFFSET :APL1:

The models are namespaced, that's why there's an alias with the same classname... But I've also tried using ThingGroups::class."created_on" to no avail.

Bonus

I wanted to know if nested relations could work, as in the commented line in the find() call. Is that possible, to make up for nested JOINs?



43.9k

Hi,

what about if you use the full namespace of ThingGroups model ?



145.0k
Accepted
answer
edited Aug '16

You need to use query builder or ::query(). Find doesn't know anything about your relation. Find is typically a shorthand for easier selecting model from which you want to select, but you can't join with it.