我的问题类似于here on Phalcon forum和here 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();
}
}
鉴于:
,你将如何表现呢?parts_id
和robots_id
(否则会触发验证错误)答案 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);
}
}