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

[2.0.3] Related Models are not saved

In the Documentation it is pointed that the related attributes can be added as array

<?php

// Get an existing artist
$artist = Artists::findFirst('name = "Shinichi Osawa"');

// Create an album
$album          = new Albums();
$album->name    = 'The One';
$album->artist  = $artist;

$songs = array();

// Create a first song
$songs[0]           = new Songs();
$songs[0]->name     = 'Star Guitar';
$songs[0]->duration = '5:54';

// Create a second song
$songs[1]           = new Songs();
$songs[1]->name     = 'Last Days';
$songs[1]->duration = '4:29';

// Assign the songs array
$album->songs = $songs;

// Save the album + its songs
$album->save();

But it seems like it does not work anymore. I don't know if its only in Version 2.0.3 or if this error occured earlier.

I have an Order Entity that contains multiple related Entities.

<?php

class Order extends \Phalcon\Mvc\Model {
    ...
    public function initialize()
    {
        parent::initialize();

        $this->hasOne('id', 'Order\Address', 'order_id', array(
            'foreignKey' => array(
                'action' => \Phalcon\Mvc\Model\Relation::ACTION_CASCADE
            ),
            'alias' => 'address',
        ));

        $this->hasOne('id', 'Order\Payment', 'order_id', array(
            'foreignKey' => array(
                'action' => \Phalcon\Mvc\Model\Relation::ACTION_CASCADE
            ),
            'alias' => 'payment',
        ));

        $this->hasMany('id', 'Order\Lodging', 'order_id', array(
            'foreignKey' => array(
                'action' => \Phalcon\Mvc\Model\Relation::ACTION_CASCADE
            ),
            'alias' => 'lodging',
        ));
    }
    ...
    /**
     * @param Lodging $lodging
     */
    public function addLodging(Lodging $lodging)
    {
        if ($lodging->getOrderId() && $lodging->getOrderId() != $this->getId()) {
            throw new \InvalidArgumentException('The Lodging belongs already to another Order');
        }

        if ($this->getId()) {
            $lodging->setOrderId($this->getId());

            $lodging->save();
        } else {
            if ($this->lodging instanceof \Phalcon\Mvc\Model\Resultset\Simple) {
                $this->lodging = $this->lodging->toArray();
            }

            array_push($this->lodging, $lodging);
        }
    }
    ...
}

Every Entity is saved correctly (Addresses and Payments) but only the lodging is not saved if i trigger $order->save().

If i try and call $lodging->save() the Entity is saved correctly.

What am i doing wrong or is it a bug?

Can you also post the other 2 model definitions (for many-to-many relationship)?

Also, just out of curiousity can you try using $Model->create(); instead of save()?