How can push an array or object to mongodb with yii

Published on Author Code Father

The solution long time ago and i thought i should share it here. So i am pushing the 1st object in mileage node like that:

$model = Customer::findOne($customerId);
if ($model->load(Yii::$app->request->post())) {
    $mileage = new mileage(2, 'British Airways', 'Usman', 10000);
    $model->mileage = array($mileage);
    $model->save();
    return $this->redirect(['view', 'id' => (string) $model->_id]);
}

So to add another object in mileage node, what we need to do is we need to get the customer object from database and we have to check if there is already an object added in the mileage node and then i have to get that object and push the newly created mileage array/object in it. modified code is below:

$model = Customer::findOne($customerId);
if ($model->load(Yii::$app->request->post())) {
    $mileage = new mileage(2, 'British Airways', 'Kamran', 9000);
    if (empty($model->mileage) || count($model->mileage) == 0) {
        $model->mileage = array($mileage);
    } else {
        $allUsedMiles = $model->mileage;
        array_push($allUsedMiles, $mileage);
        $model->mileage = $allUsedMiles;
    }
    $model->save();
    return $this->redirect(['view', 'id' => (string) $model->_id]);
}

I hope this will help someone in the future 😉 Thanks,

Comments

comments