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

Create model relation from e.g. beforeSave

HI all

Is it possible by in any way to set/create a model relation within a model. The case would be something like

<?php

use Phalcon\Mvc\Model;

class Robot extends Model
{
    public function beforeCreate()
    {
        $this->RobotParts = new RobotParts();
    }

This should then create a default RobotParts model and create this. Any other suggestions to solve this are welcome. It is basically to create a default default relation from a model.

Thanks

edited May '16

You need to use magic __set method if you want to make it works. At least if you really want to save it, not to be just some virtual robotParts which don't really exists in database.

edited May '16

I have tested something like this and it does not seems to work as I would expect.

<?php

use Phalcon\Mvc\Model;

class Robot extends Model
{
    public function beforeCreate()
    {
        $RobotParts =  = new RobotParts();
        $this->__set('RobotParts',$RobotParts);
    }

No RobotParts is created if I run $Robot->create()?

edited May '16

But you have relations made right ? Also i dont see were you setting values for RobotParts. You are just creating RobotParts without setting robot and part id.



11.6k
edited May '16

Why you need an empty $robotsParts? the usual way: if you have defined your relation, create a related model instance and populate it in your controller at the same time you create a robot, assign it to $robot->relationAliasName, save the $robot, $robotsParts will be created in your db automatically. maybe I'm missing something...from my point of view, you don't need the robot to have robots parts until a robotPart exist, no?