Rahman
Rahman

Reputation: 452

How to save a model in json in yii2?

I have a model like follow:

$book = \backend\models\Book::find()->all();

then I can access to special column value by follow statement:

$ID = $book[0]['ID'];

Now I want to convert this model to Json and save it in DB. therefore I've write bellow code:

$json = json_encode($book);

then I want to load and decode it.

$object = json_decode($json) ;
$ID = $object[0]['ID'];

but I can't. I don't know what should I do for this purpose. is it possible that convert a model to json?

can anyone help me to solve this problem?

Upvotes: 1

Views: 7181

Answers (3)

Luna
Luna

Reputation: 2322

Try this:

$book = \backend\models\Book::find()->asArray()->all();
$json = json_encode($book);
$data = json_decode($json, true);
print_r($data[0]['ID']);

Add ->asArray() when querying

Upvotes: 2

Rahman
Rahman

Reputation: 452

thanks for all answers. I wanted to save all model as a json or string in DB and then retrive it and use as a model again. so I've solved this problem by serialize()

$book = \backend\models\Book::find()->all();
$str = serialize($book);
$object = unserialize($str);
$ID = $object[0]['ID'];

Upvotes: 0

Maksym Fedorov
Maksym Fedorov

Reputation: 6456

json_decode converts data to StdObject by default. If you want to work with an array instead of an object, you should set assoc parameter to true

$object = json_decode($json, true) ;
$ID = $object[0]['ID'];

If your json is empty then you must configure [fields][1] method to correct data export. For example:

class Book extends ActiveRecord
{
    // some code

    public function fields()
    {
        return [
            'id',
            // others attributes of Book model
        ];
    }
}

Upvotes: 2

Related Questions