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

Method find with "columns" parameter and BelongsTo

Hi, I have a table notices with the following cols: id, name, id_templates, active, emails id_templates belongs to templates.id. This is set in the model this way:

$this->belongsTo(
        'id_templates',
        'Templates',
        'id',
        array(
            'alias' => 'template'
        )
    );

Now I want to make this query:

Notices::find(array("columns" => "name, Templates.name, active, emails"));

But it returns this error:

Phalcon\Mvc\Model\Exception: Unknown model or alias 'Template' (11), when preparing: SELECT name, Template.name, active FROM [Notices]

And if I do it with the query method it returns ok:

self::query()
        ->columns("Notices.id as id, Notices.name as name, Templates.name as template, Notices.active as active")
        ->leftJoin("Templates")
        ->leftJoin("Reports")
        ->leftJoin("NoticesConf")
        ->order("name ASC")
        ->execute()

I have to do it with the Find method because I override it in a ModelBase, or the ability to override the query function an add it into a ModelBase a $start(microtime) / query / $end(microtime)



145.0k
Accepted
answer

There is no way to do it with ::find() method. Find don't support joins itself. It's only for selecting models within model. You need to use query builder.

Any idea about override Query method in my ModelBase?

There is no way to do it with ::find() method. Find don't support joins itself. It's only for selecting models within model. You need to use query builder.

But why you want odo such a things ? Just better create repository classes and use there query builder and in your controller/service whatever just do $repository->findXyz();