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.

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 invoiceid IS NULL AND ThingGroups.createdon <= :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?



44.9k

Doing a normal find doesn't know that it is supposed to be joining. Try to either create a full Phalcon\Mvc\Model\Query using PHQL or first get a Things model and then use the conditions in the related call like $thing->getThingGroups(["conditions" => ...]).



30.0k

Hi,

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



99.6k
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.