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

Saving array resultset

Hi all. I need to run a method that repair my utf8 texts that are broken by a bad migration. I have a php function that do strreplace on several chars and i want it to run on every column of several tables. To do that I need to transform the resultset in array, and than to save it, but... how do I save a model object when it is converted in array?

use Phalcon\Utils\Encoding;
use Phalcon\Mvc\Model\Resultset;

// ...

public function repairTableEncodingAction(array $params)
{
    if (!isset($params[0])) {
        echo "Manca il nome della tabella" . PHP_EOL;
        return -1;
    }

    $table = "\\App\\Models\\" . ucfirst(strtolower($params[0]));
    $items = $table::find();

    // Return every item as an array
    $items->setHydrateMode(Resultset::HYDRATE_ARRAYS);

    foreach ($items as $k => $item) {
        foreach ($item as $column=>$value) {
            $items[$k][$column] = Encoding::fixUTF8($value);
        }
    }

    // Return every item as a stdClass
    $items->setHydrateMode(Resultset::HYDRATE_OBJECTS);

    foreach ($items as $item) {
        //need to save but it doesn't work .
        $item->save();
    }

    echo "Corrette tutte le colonne" . PHP_EOL;
}


32.3k
Accepted
answer
edited Nov '17

Hi @cosimo to use save() you have to use >setHydrateMode(\Phalcon\Mvc\Model\Resultset::HYDRATE_RECORDS);

Hydrations modes info

Good luck



12.1k

Thank you very much! I was sure that HYDRATE_OBJECTS should have done the same things of HYDRATE_RECORDS