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

Model not saving related records

I have a model, Request, that has some related records, $items. I can't get $items to update when I save() the Request.

When saving, $items is an array of models. I have set up the proper hasMany() relationship between Request and $items.

This saving was working earlier, when $items was a Simple ResultSet. Now that I've changed it to just an array, no saving gets done.

No validation errors are being generated, and no SQL is happening related no the items.

Screw it. I'm getting nowhere so I've just reverted back to doing individual delete() and save() calls on the items. The transactional nature is lost.

I know about that page. I was essentially doing the same thing as the second example, but nothing was being saved. I've moved on though, so it's a bit of a moot point.



9.2k
edited Jul '14

Have you ever unit tested deleting the hasManyToMany with

array(
     'foreignKey' => array(
          'action' => Phalcon\Mvc\Model\Relation::ACTION_CASCADE
      )
)

seems not to work.

It only worked for me if I manually delete the connected table and the child model like

$parent = ParentModel::findFirst();
foreach($parent->children as $child){
    $link = ParentChildLink::findFirst(array("parentId = ?0 and childId = ?1","bind" => array($parent->id,$child->id)));
    $link->delete();
    $child->delete();
}
$parent->delete();

+1 In version 1.2.5 don't work as in documentation. Work when adding one element like in example one song (https://docs.phalcon.io/en/latest/reference/models.html#storing-related-records), but when trying add array of songs don't want to work. Not adding anything.



558

Since I recently ran into a similar problem I found this thread. My setup is:

  • phalcon 1.3.1
  • apache 2.2.26
  • php 5.5.13
  • OS X Mavericks

Here's what I found experimenting with this. Lower case aliases ('artists', 'songs') don't seem to work whereas upper case aliases ('Artists', 'Songs') do.

To add one element this worked:

$this->Elements = $element;

To add multiple elements this worked:

$elements = array($element1, $element2);
$this->Elements = $elements;

After that I had to save the object before accessing the elements again. When I didn't, phalcon would just return a result set with only the elements already in the database.

Am I doing something seriously wrong or what?



4.0k
edited Jul '14

I was having the same problem and after I saw Nates post, I was able to save a relation.