1

I have a Product model and Product controller:

public function actionGet($id) {
    Yii::$app->response->format = Yii\web\Response::FORMAT_JSON;
    return ['product' => Product::findOne($id)];
}

In my DB, I got products.images column, there's an array with images:

["product.png", "product2.jpg"]

When I do an request to /products/get?id=1, I have a response with the string images, but I need an array with images. How to convert images to array in Product model? Thanks in advance!

1 Answer 1

2

You can't save this ["product.png", "product2.jpg"] as an array in the DB. This is just text.

You can however save a json string rep of your array. ie:

public function beforeSave($insert)
{
    if(isset($this->images) && is_array($this->images))
      $this->images = \yii\helpers\Json::encode($this->images);
    return parent::beforeSave($insert);
}

Then you can decode this using afterFind:

public function afterFind()
{
    if(isset($this->images)
        $this->images = \yii\helpers\Json::decode($this->images);
    return parent::afterFind();
}
Sign up to request clarification or add additional context in comments.

2 Comments

afterSave() method requires $changedAttribute array. What should I pass here?
@Alexxosipov It will be beforeSave() not afterSave(). Change to parent::beforeSave()

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.