3
我的問題與here on Phalcon forum和here as well描述的類似。更新記錄的N-N關係
我目前使用下面的代碼來編輯多對多關係。
這裏是模型:
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記錄由一套新的替換,而無需顯式地DELET'ing他們
- (B)有沒有必要明確聲明新的機器人部件記錄,因爲唯一必需的字段是
parts_id
和robots_id
(否則,驗證錯誤會被觸發) - (C)零件被分配,而不是RobotsParts(我無法獲得這部分工作,儘管上面提到的相關帖子中有所說)