1. 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?

Discussion in 'XenForo Development Discussions' started by Jaw.sh, Feb 18, 2015.

  1. Jaw.sh

    Jaw.sh Member

    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:

            // 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?
  2. Chris D

    Chris D XenForo Developer Staff Member

    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.
  3. Jaw.sh

    Jaw.sh Member

    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?

    The existing data required by the data writer could not be found.
  4. Chris D

    Chris D XenForo Developer Staff Member

    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))

Share This Page