Search code examples
phpmodelsphalcon

Phalcon find with columns parameter returns rows instead models


When I use Model::find() response is Resultset of Models, but when I add columns parameter to restrict returned columns the response is Resultset of Rows.

Example:

// Resultset of Models
$users = \Models\Users\Users::find();

// Resultset of Rows
$users = \Models\Users\Users::find([
        'columns' => 'id, email'
]);

That makes me unable to call model methods. Is there a way to have Resultset of Models with columns restriction in ::find() method? I'm not sure, but this seems like bug, since Phalcon docs says:

While findFirst() returns directly an instance of the called class (when there is data to be returned), the find() method returns a Phalcon\Mvc\Model\Resultset\Simple.

And there is nothing about the exception of this rule when using columns parameter.

I would also note that other parameters of ::find() like condition, order, bind etc. works fine (Models returned).

Phalcon 1.3.4


Solution

  • This is not a bug, it is the expected behaviour. Info in the docs scroll a bit down to the Parameters table and read description of columns.

    If you need to use model methods or relations you should not specify columns. But if you are after better performance and do not need model relations you should use the Query Builder.

    Rest of the find() parameters like condition, order e.t.c. will, not affect your ability to use model methods.

    The findFirst() method is also working like the find() method. Example here:

    No columns specified:

    News::findFirst(3);
    
    // Output
    Models\News Object
    (
    ...
    

    When specifying columns

    News::findFirst([
        'columns' => 'id, created_at'
    ]);
    
    // Output
    Phalcon\Mvc\Model\Row Object
    (
        [id] => 1
        [created_at] => 2016-02-02
    )