У меня есть модель X, которая имеет отношение многих ко многим с моделью Word. В контроллере модели X у меня есть пользовательский виджет формы, который отправляет wordId через ajax и сохраняет это отношение:
public function onAddWord()
{
$wordId = post($this->getFieldName());
if (is_numeric($wordId)) {
$this->model->words()->syncWithoutDetaching([$wordId]);
} else {
// if the word that user selected, was not in the list, wordId does not contain any ID,
// but it's the actual new word the needs to be added to the words table
$newWord = WordModel::create(
[
'word' => $wordId,
'lang_id' => 2,
]
);
$this->model->words()->attach($newWord->id);
}
// refresh the relation manager list
return $this->controller->relationRefresh('related_words');
}
Это прекрасно работает, когда я обновляю модель X. Но когда я Находясь на странице create
модели X, сохранить вышеуказанные отношения не удается, поскольку модель X еще не существует. Я пытался использовать различную привязку, но она не работала:
public function onAddWord()
{
$sessionKey = $this->controller->formGetSessionKey();
$wordId = post($this->getFieldName());
if (is_numeric($wordId)) {
$this->model->words()->syncWithoutDetaching([$wordId]);
} else {
// if the word that user selected, was not in the list, wordId does not contain any ID,
// but it's the actual new word the needs to be added to the words table
$newWord = WordModel::create(
[
'word' => $wordId,
'lang_id' => 2,
], $sessionKey
);
$this->model->words()->attach($newWord->id, $sessionKey);
}
// refresh the relation manager list
return $this->controller->relationRefresh('related_words');
}
Как я могу сделать эту работу?