Convert array to string in Doctrine for simple_array field

I would like to import data from a JSON file into a database table. I am using Doctrine with pdo_sqlite driver and set up the following entity:

/**
 * @Entity @Table(name="mytable")
 **/
class MyClass
{
    /** @Id @Column(type="integer") @GeneratedValue *
     * @Column(type="integer")
     */
    var $id;

    /** @Column(type="string") **/
    var $name;


    /** @Column(type="simple_array") **/
    var $parameters;

    function __construct($name, $parameters)
    {
        $this->name = $name;
        $this->parameters = $parameters;
    }

    // getters and setters here
}

      

I created a simple import method:

function importFromJson($tableName, $fileName)
    {
        if (file_exists($fileName)) {
            $data = json_decode(file_get_contents($fileName));
            if (is_array($data)) {
                $connection = getEm()->getConnection();
                foreach($data as $tuple) {
                    if (is_object($tuple)) {
                        $connection->insert($tableName, (array)$tuple);
                    }
                }
            }
        }
    }

      

My import.json file contains the following text:

[
  {
    "name": "A name",
    "parameters": ["a","b","c"]
  }
]

      

When I call my import method:

importFromJson("mytable", "import.json");

      

I am getting the following error:

An exception occurred while executing "INSERT INTO mytable (name, parameters) VALUES (?,?) 'With parameters [" Name ", [" a "," b "," c "]]:

Convert array to string C: \ MyProject \ vendor \ doctrine \ DBAL \ Lib \ Doctrine \ DBAL \ DBALException.php: 119 C: \ MyProject \ vendor \ doctrine \ DBAL \ Lib \ Doctrine \ DBAL \ connection.php: 996 C: \ MyProject \ Vendor \ Doctrine \ DBAL \ Lib \ Doctrine \ DBAL \ connection.php: 696 C: \ MyProject \ Lib \ import.php: 39

Isn't the specific purpose of the simple_array type to convert arrays to strings that can be stored in the database?

+3


source to share


1 answer


I don't know why you have to store the parameters as an array in the DB, but the easy way to store it first, you have to convert parameters

to a valid string, otherwise it cannot be stored correctly.

foreach($data as $tuple) {
    if (is_object($tuple)) {
        $touple = implode(",", (array)$touple);
        $connection->insert($tableName, (array)$tuple);
    }
}

      

another option might be to convert it as json string



foreach($data as $tuple) {
    if (is_object($tuple)) {
        $touple = json_encode($touple);
        $connection->insert($tableName, (array)$tuple);
    }
}

      

And to be able to use the data when in use select

, you have to convert the data back to an array using again explode()

or json_encode

. Hope it will be! :)

0


source







All Articles