我正在运行SilverStripe 3.4
我找不到任何关于以编程方式保存许多关系额外字段的文档.以下代码根本不起作用:
foreach ($notifications as $notification) {
$status = $notification
->Members()
->filter([
"ID" => Member::currentUserID()
])
->first();
$data['Read'] = $status->Read; // whenever I call this code, $status->Read is ALWAYS 0
$status->Read = 1;
$status->write();
}
ORM类:
class Notification extends DataObject {
private static $belongs_many_many = [
"Members" => "Member"
];
}
class Member extends DataObject {
private static $many_many = array(
"Notifications" => "Notification"
);
private static $many_many_extraFields = array(
"Notifications" => array(
"Read" => "Boolean"
)
);
}
我已经看到DataObject :: getChangedFields过滤掉了我的Read字段,因为它不是“数据库字段”
注意:我已覆盖Notification :: onBeforeWrite但是:
>我不认为这是被称为
>我在开头就有这个代码:
protected function onBeforeWrite() {
parent::onBeforeWrite();
$changedFields = $this->getChangedFields();
if (isset($changedFields['Read']) && count($changedFields) == 1) {
return;
}
}
最佳答案 我找到了反直觉的答案:
foreach($notifications as $notification){
$data = $notification->toMap();
$list = $notification->Members()
->filter([
"ID"=>Member::currentUserID()
]);
$status = $list->first();
$data['Read'] = $status->Read;
$list->add(Member::currentUserID(),[
"Read"=>1
]);
}
这没有任何意义(将已经列在列表中的内容添加到列表中),但它确实有效.我希望他们更新这个.