更新记录的N-N关系

时间:2014-04-29 20:42:25

标签: model phalcon

我的问题类似于here on Phalcon forumhere as well所描述的内容。

我目前使用以下代码编辑多对多关系。

以下是模型:

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");
    }

}

这是当前的控制器:

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()

以下是我希望控制器看起来像:

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();

    }

}

鉴于:

,你将如何表现呢?
  • (A)前一组RobotsParts记录被新组替换,无需明确删除它们
  • (B)没有必要明确声明新的RobotsParts记录,因为唯一必需的字段是parts_idrobots_id(否则会触发验证错误)
  • (C)部件被分配,而不是RobotsParts(尽管上面提到的相关文章中有说法,但我无法使这部分工作)

1 个答案:

答案 0 :(得分:3)

发生(B)/(C)问题是因为Phalcon没有将ResultSetInterface注册到ManyToMany属性中。

解决方法:

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);
    }

}
相关问题