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 call methods of a model when looping resultset?

I have a method in a model like this:

class Poet extends \Phalcon\Mvc\Model
{
    public function getFullName()
    {
        return $this->firstName . ' ' . $this->lastName;
    }
}

In my controller I tried to do

$poets = Poet::find();

$i = 0;
foreach($poets as $poet) {
    $fullName = $poet->getFullName();
    $output['poets'][$i] = array(
        'id' => $poet->id,
        'name' => $fullName,
    );

    $i ++;
}
$this->view->setVars($output);

But it seems items in resultset is not an instance of Poet but instance of Model\Row

cause it says:

Call to undefined method Phalcon\Mvc\Model\Row::getFullName() in .......

My question is, how should I do something like this, or is there any way to get the instance of the model of a row object?

it must be instance of Poet, only that method cannot be found

@digitronac But according to the document, findFirst() returns an instance of Phalcon\Mvc\Model (which should be Poet) but find() returns an instance of Phalcon\Mvc\Model\Resultset, while each item in it is an instance of Phalcon\Mvc\Model\Row.



300
Accepted
answer

well, Poet is instance of Phalcon\Mvc\Model\Row and resultset should be made out of those ...

try doing:

$poets = Poet::find();

foreach($poets as $poet) { var_dump(get_class($poet)); }

expected result should be string "Poet"

@digitronac

Oh, you are right!

When I just use find(); get_class($poet) give me "Poet"

but if I specific columns like

$poets = Poet::find(array('columns' => 'id'));

get_class($poet) give me "Row" which don't have that method defined in class Poet

Did I do anything wrong?



98.9k

Specifiying columns in find() will return an incomplete object:

$poets = Poet::find(array('columns' => 'id'));

This is mentioned in the docs:

Return specific columns instead of the full columns in the model. When using this option an incomplete object is returned

https://docs.phalcon.io/en/latest/reference/models.html#finding-records