【问题标题】:Many Many Extra Field not saving许多许多额外的字段不保存
【发布时间】:2016-07-20 23:29:34
【问题描述】:

我正在运行 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;
        }
    }
    

【问题讨论】:

  • 您的意思是要覆盖 Member 类吗?它由框架提供,在这种情况下它可能具有优先权。为了争论起见,当您将 Member 的名称更改为 MyMember 时会发生什么?它会保存吗?
  • @elliot_at_silverstripe 我们正在使用 DataExtensions

标签: php silverstripe


【解决方案1】:

我找到了反直觉的答案:

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

这没有任何意义(将列表中已经存在的内容添加到列表中),但它有效。我希望他们更新这个。

【讨论】:

  • 如果您更改元素本身的某些内容(在本例中为成员),它将被保存到成员表中。因此会自动更新。 $many_many_extraFields 保存到数据库中的一个额外表中,在您的示例中为 Member_Notifications。因此,当您从 ManyManyList 中获取元素时,您会立即失去与列表的关系。您只拥有具有额外 manymany 信息的元素。因此,您不需要更新 Member DO,而是更新 ManyManyList。我希望这有助于使工作示例更直观;)
  • 为什么一定要失去关系?您在那里有架构(在 $many_many 中),我确信可以在检查标准对象属性的同时检查许多关系额外字段
  • 另外,为什么ManyManyList::add 方法不仅仅是添加东西? add 方法会更新内容似乎并不直观
猜你喜欢
  • 2011-06-28
  • 1970-01-01
  • 2011-04-20
  • 1970-01-01
  • 2023-04-10
  • 2017-07-02
  • 1970-01-01
  • 2014-05-03
  • 1970-01-01
相关资源
最近更新 更多