We have moved our forum to GitHub Discussions. For questions about Phalcon v3/v4/v5 you can visit here and for Phalcon v6 here.

Has Many relation only persist the last record

Hi all, i am having troubles to persist related records on a 1:n relation.

I have a rate plan table, and i want keep the pricing history of each rate plan. So i have the next database schema:

So, i wrote the model classes as below.

RatePlans.php

    public $id;
    public $name;
    public $slug;
    public $price;
    public $active;

    public function initialize()
    {
        $this->hasMany('id', 'PricingHistory', 'rate_plans_id', [
            'alias' => 'pricing_history'
        ]);
    }

    public function get_source()
    {
        return 'rate_plans';
    }

    public function getPricingHistory($parameters = null)
    {
        return $this->getRelated('pricing_history', $parameters);
    }

PricingHistory.php

    public $id;
    public $price;
    public $time;

    public function initialize()
    {
        $this->belongsTo('rate_plans_id', 'RatePlans', 'id');
    }

    public function get_source()
    {
        return 'pricing_history';
    }

Before change the rate plan price, i created a new PricingHistory model and set the relation between models as below:

            $history = new PricingHistory();
            $history->price = $aModel->price;
            $history->time = time();
            // $aModel is an instance of RatePlans model
            $aModel->pricing_history = array($history);
            $aModel->save();

The last code persist only the last price history record, overwriting other records related to current rate plan. So, i have only one history record per rate plan.

What is wrong with the model mapping ? Or the relation insert ?

Thanks.



1.9k
edited May '16

If I assume good, it need to be

$aModel->pricing_history[] = $history;

$aModel->save();

Thanks for reply, but doesn't work for me.

If I assume good, it need to be

$aModel->pricing_history[] = $history;

$aModel->save();


4.5k
Accepted
answer

Sory, was my fault. The PricingHistory model had validation errors. Now, i can persist related records.