Solved thread

This post is marked as solved. If you think the information contained on this thread must be part of the official documentation, please contribute submitting a pull request to its repository.

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;
}


9.0k
Accepted
answer
edited 13d ago

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

Hydrations modes info

Good luck



1.8k

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