Elvex
Elvex

Reputation: 671

Update a record's N-N relationships

My issue is similar to what is described here on Phalcon forum and here as well.

I currently use the following code to edit a Many-to-Many relationship.

Here is the model :

class Robots extends \Phalcon\Mvc\Model
{
    public $id;
    public $name;

    public function initialize()
    {
        $this->hasMany(
            "id", "RobotsParts", "robots_id");
        $this->hasManyToMany(
            "id", "RobotsParts", "robots_id",
            "parts_id", "Parts", "id");
    }

}

Here is the current controller :

public function showRobot($id)
{
    // Find the current Robot
    $robot = Robots:find($id);

    // Someone asked to rebuild the robot ?
    if ($this->request->isPost())
    {
        // Identify the new parts
        $parts = Parts::findIn($this->request->getPost('parts_ids'));

        // (A) Robot is dismantled
        $robot->robotsParts->delete();

        // (B) Create a new set of relationships
        $robotsParts = array();
        foreach($parts as $part)
        {
            $robotPart = new robotsParts();
            $robotPart->parts_id = $part->id;
            $robotsParts[] = $robotPart;
        }

        // (C) Assign new relationships to the Robot
        $robot->robotsParts = $robotsParts

        // Save
        $robot->save();

    }

}

@see \Phalcon\Mvc\Model::findIn()

Here is what I'd like the controller to look like :

public function showRobot($id)
{
    // Find current Robot
    $robot = Robots:find($id);

    // Someone asked to rebuild the robot ?
    if ($this->request->isPost())
    {
        // Identify the new parts
        $parts = Parts::findIn($this->request->getPost('parts_ids'));

        // Relate new parts to the Robot
        $robot->parts = $parts;

        // Save
        $robot->save();

    }

}

How would you perform it, given that :

Upvotes: 3

Views: 2073

Answers (1)

Elvex
Elvex

Reputation: 671

The (B)/(C) problems occur because Phalcon doesn't register a ResultSetInterface into a ManyToMany property.

Workaround :

abstract class AbstractModel extends \Phalcon\Mvc\Model
{

    public function __set($property, $value)
    {
        if ($value instanceof \Phalcon\Mvc\Model\ResultSetInterface)
        {
            $value = $value->filter(function($r) {
                return $r;
            });
        }
        parent::__set($property, $value);
    }

}

Upvotes: 3

Related Questions