PHP code example of archipro / silverstripe-db-json

1. Go to this page and download the library: Download archipro/silverstripe-db-json library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

archipro / silverstripe-db-json example snippets



use SilverStripe\ORM\DataObject;
use ArchiPro\Silverstripe\DbJson\DBJson;

class MyDataObject extends DataObject
{
    private static $table_name = 'MyDataObject';

    private static $db = [
        'Payload' => DBJson::class,
    ];
}



$myDataObject = MyDataObject::create();
$myDataObject->Payload = [
    'key' => 'value',
];

$myDataObject->write();

var_dump($myDataObject->Payload);
// array(1) {
//   ["key"]=> string(5) "value"
// }

$one = MyDataObject::create();
$myDataObject->Payload = [
    'meta' => [
        'Title' => 'My page',
        'Created' => '2024-01-01',
        'Author' => 'John Doe',
    ]
];
$myDataObject->write();

// ...

// This will return all objects where the `Author` field in the `meta` array is `John Doe`
$list = MyDataObject::get()->filter('Payload:Json', ['$.meta.Author' => 'John Doe']);

// This will return all objects where the `meta` array contains the `Title` and `Created` fields with the provided values
$list = MyDataObject::get()->filter(
    'Payload:Json',
    ['$.meta' => ['Title' => 'My page', 'Created' => '2024-01-01']]
);

$list = MyDataObject::get()->filter('Payload:Json:not', ['$.meta.Author' => 'John Doe']);

// The following query will extract the price from the Payload column and only
// return records with a price greater than 4
$list = MyDataObject::get()->where([
    'JSON_EXTRACT("Payload", ?) > ?' => ['$.price', 4],
]);