• This site uses cookies. By continuing to use this site, you are agreeing to our use of cookies. Learn more.

Update or Insert - DataWriter Magic Method for Handling ifs?

Jawsh

Formerly null0
#1
I have a session activity table.

user_id, activity_message, activity_heartbeat (to simplify things).

If you send a message, this gets inserted.
1, 1424255677, null

If you heartbeat a second after, this should be the result:
1, 1424255677, 1424255678

But I'm having an immense amount of trouble figuring out how to do this without writing a bunch of custom queries.

In my mind, this should work:

Code:
        // Commit the activity to database.
        // Fetch writer.
        $writer = $this->_getDataWriter( );
      
        // Set user ID.
        $writer->set( 'user_id',           $user_id );
      
        // Set each field to the specified time.
        foreach( (array) $activities as $activity ) {
            $writer->set( $activity,       is_null( $time ) ? XenForo_Application::$time : (int) $time );
        }
      
        // Commit and return.
        return $writer->save();
But, it doesn't. It works once, then subsequent updates throws duplicate PK errors. Even my work's custom framework has a way to deal with updating or inserting but DataWriting with XenForo appears oddly insufficient despite its many positives.

What should I be doing for this?
 

Chris D

XenForo developer
Staff member
#2
The setExistingData method will find the required record then subsequent "sets" on that writer will be done as updates.

You can use various methods depending on what you need to get the data back after setExistingData has been set e.g get, getExisting, getMergedData etc.
 

Jawsh

Formerly null0
#3
The setExistingData method will find the required record then subsequent "sets" on that writer will be done as updates.

You can use various methods depending on what you need to get the data back after setExistingData has been set e.g get, getExisting, getMergedData etc.
This works really well for updates, but now it's not inserting new rows. What do I need to wrap around, or do to, setExistingData so that we can create a row if it's PK isn't already extant?

Code:
The existing data required by the data writer could not be found.
 

Chris D

XenForo developer
Staff member
#4
When the DataWriter is created, the second parameter is the error level.

Search XF files for ERROR_SILENT for an example of how that can be used.

You can then do:

if ($dw->setExistingData($data))