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

Phalcon\Mvc\Model\Resultset\Simple - WTF???? / Nasty bug

A nasty bug I've found:

That works okay:

$comps = \space\companies\EntityCompany::find( ['limit' => 5] );

echo '<pre>';

$comps->next(); print_r( $comps->current()->toArray() ); echo '<br />';
$comps->next(); print_r( $comps->current()->toArray() ); echo '<br />';
$comps->next(); print_r( $comps->current()->toArray() ); echo '<br />';
$comps->next(); print_r( $comps->current()->toArray() ); echo '<br />';
$comps->next(); print_r( $comps->current()->toArray() ); echo '<br />';

Now WHY it doesn't working ($comps->current() is returning NULL)???

$comps = \space\companies\EntityCompany::find( ['limit' => 1] );

echo '<pre>';
$comps->next(); print_r( $comps->current()->toArray() ); echo '<br />';

That is working OK:

$comps = \space\companies\EntityCompany::find( ['limit' => 1] );

echo '<pre>';

foreach ($comps as $entity) {
    print_r( $entity->toArray() );
}

According the docs (https://docs.phalcon.io/4.0/en/db-models#model-resultsets), because it need to be rewinded before.

$invoices->rewind();
while ($invoices->valid()) {
    $invoice = $invoices->current();

    echo $invoice->inv_title, PHP_EOL;

    $invoices->next();
}

If you want to pick first row use getFirst() instead.
This method make the same code as above

    /**
     * Get first row in the resultset
     */
    public function getFirst() -> <ModelInterface> | null
    {
        if this->count == 0 {
            return null;
        }

        this->seek(0);

        return this->{"current"}();
    }

Source: https://github.com/phalcon/cphalcon/blob/master/phalcon/Mvc/Model/Resultset.zep#L333

I don't uderstand why I need to rewind it when there is only one record in resultset, and I don't need to rewind it when there are more than one? Docs doesn't say anothing about it.

Because you started with next(), which advances the offset from 0 to 1, and then called current().

I don't uderstand why I need to rewind it when there is only one record in resultset, and I don't need to rewind it when there are more than one? Docs doesn't say anothing about it.

current() does the same thing - returns null, no matter which example - that with one record or five, anyway I uderstand that rewind is always necessary.