Many additional fields are not saved.

I am running SilverStripe 3.4

I cannot find documentation on programmatically storing many additional relationships. The following code just won't work:

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 classes:

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

It looks like I saw it DataObject::getChangedFieldsfiltering my field Readbecause it is not a "database field"

Note. I redefined Notification::onBeforeWrite, but:

  • I do not think this is called
  • I have this code at the beginning of it:

    protected function onBeforeWrite() {
        parent::onBeforeWrite();
        $changedFields = $this->getChangedFields();
        if (isset($changedFields['Read']) && count($changedFields) == 1) {
            return;
        }
    }
    
+4
source share
1 answer

I found a counter intuitive answer:

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

It doesn't make sense (adding something that is already on the list to the list), but it works. I hope they update it.

+2
source

Source: https://habr.com/ru/post/1648582/


All Articles