Eloquent how I can parse postgresql's hstore?

250 Views Asked by At

An eloquent model uses the following table and it is stored in a postgresql database:

name: table
id: PK SERIAL
values: HSTORE

And the model is named TableModel

namespace App;
use Illuminate\Database\Eloquent\Model;
class TableModel extends Model
{
   protected $table = 'table';
}

But once I retrieve the value value I get the following response using tinker session:

$model = Model::find('1');
$model->value;
""name"=>"Namae", "value"=>"55""

How I can retrieve either the name or the value from the value column.

2

There are 2 best solutions below

0
Dimitrios Desyllas On BEST ANSWER

Hstore is simply a format in a form of

"key" => "Value","key"=>"value"

As seen in https://www.postgresql.org/docs/11/hstore.html

And easily can be converted into json by replacing the => into : and enclosing the string into {} a sample code to do this is (continuing the tinker session you mention in your question):

$value = $model->value;
$value = str_replace('=>',':',$value);
$value = '{'.$value.'}';
$value = json_decode($value)
1
Slava Rozhnev On

Because hstore format equal to php format you can use PHP eval function:

$hstore = '"name"=>"Namae", "value"=>"55"';

eval('$d=['.$hstore.'];');

printf("The value is %s \n", $d["value"]);

PHP online fiddle