首页 > 解决方案 > OctoberCMS:附加关系时如何使用延迟绑定?

问题描述

我有一个模型 X,它与 Word 模型具有多对多关系。在 X 模型的控制器中,我有一个自定义表单小部件,它通过 ajax 提交 wordId,并保存该关系:

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

我怎样才能使这项工作?

标签: phpoctobercmsoctobercms-backend

解决方案


推荐阅读