Created
April 15, 2019 16:08
-
-
Save webdevilopers/d111fc9b3272bb0e09e1c968c65c3eb9 to your computer and use it in GitHub Desktop.
UPDATE and INSERT statements with Doctrine DBAL and MySQL JSON type
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
class JsonObject | |
{ | |
/** @var string $result */ | |
private $result; | |
private function __construct(string $result) | |
{ | |
$this->result = $result; | |
} | |
/** | |
* @param array $array | |
* @return JsonObject | |
* @see https://elephantdolphin.blogspot.com/2016/02/mysqls-json-functions-verses-phps-json.html | |
*/ | |
public static function fromArray(array $array): JsonObject | |
{ | |
$result = ""; | |
foreach ($array as $key => $value) { | |
$result .= "'$key', '$value', "; | |
} | |
return new self(substr($result,0,(strlen($result) - 2))); | |
} | |
/** | |
* @return string | |
*/ | |
public function getResult(): string | |
{ | |
return $this->result; | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
// Initial INSERT | |
$data = ['foo' => json_encode($foo->toArray())]; | |
$dbal->connection->insert('foos', $data); | |
// Convert array to JSON Object | |
$newData = $newFoo->toArray()); | |
$object = JsonObject::fromArray($newData); | |
// UPDATE | |
$stmt = $dbal->connection->prepare(sprintf( | |
"UPDATE `foos` SET | |
foo = JSON_ARRAY_APPEND(foo, '$', JSON_OBJECT(%s)) | |
WHERE foo_id = :fooId", $object | |
)); | |
$stmt->bindValue('fooId', $data['fooId']); | |
$stmt->execute(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Here is an improved version of the method by @adelineu: