We are moving our forum in GitHub Discussions. For questions about Phalcon v3/v4 you can visit here and for Phalcon v5 here.

Saving objects with Many-to-Many relation produces an error

Hello, I'm quite new to Phalcon. I'm trying to setup models with many-to-many relation. With some struggle I managed to fetch the related entities (btw API docs don't say anything about options array for hasManyToMany), now I want to save them, but I can't. Basically what I try is:

//previously configured: 
//$a->hasManyToMany("id", "a_to_b", "a_id", "b_id", "B", "id", array("alias" => "bs"));
$a = new A();  
$a->data = "data";

$b = new B();
$b->name = "name";

$bs = array();
$bs[] = $b;
$a->bs = $bs;

And I get "b_id is required". I guess this comes from a_to_b model, because both A and B has their primary keys as just "id". If I set id manually

$b->id = 100;

Everything works fine, but this is not what I would like to do all the time. And yes, $b->id field is auto_increment. It also produces a notice: "Notice: Access to undefined property App\Model\B::id" on the $a->save() line.

I will be very thankful for a swift or just any reply.


You can save $b before call $a->save(). Then id of $b would be set.


$b = new B();
$b->name = "name";



But it should be done automatically, isn't it? As mentioned somewhere, it is also wrapped in a transaction, so that if B is not saved, A will not be saved too. So yeah, it's a workaround, but I guess it shouldn't be like that.