php - 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');
}
我怎样才能使这项工作?
解决方案
推荐阅读
- node.js - findall 多对多续集
- ruby - 从此数组创建哈希
- php - 我应该把模型创建代码放在哪里?
- javascript - 嵌套对象:更新具有相同名称的所有属性
- java - 带有mysql db连接的jpa在lagom中不起作用
- angular - 如何在 catcherror 中从订阅返回翻译后的消息?
- java - 如何使用 AngularJs 创建嵌套 Spring Boot 的结构和显示注释
- amazon-web-services - AWS - 创建新的 EC2 安全组时如何接收 SNS 警报?
- kubernetes - 如何通过 Helm 图表从 json 中读取值
- json - Eiffel 库:JSON_OBJECT.item 和获取内容的常用方法