Mark Steudel Tue Nov 22 16:39:27 -0500 2011

Subject: Associations > create or update

I'm trying out PHP.ActiveRecord and I'm trying to understand associations. I have these two models.

class User extends ActiveRecord\Model {
    // a person can have many orders and payments
    static $has_one = array(
        array('games') );

    static $validates_uniqueness_of = array( 'user_id' );
}

class Game extends ActiveRecord\Model {
    static $belongs_to = array(
        array( 'user' )
    );
}

1. When I'm declaring the association, is the "games" in the association, is that the db table name, the model name, or whatever name I want to refer to in my user object?

2. In this case, a user can only have one game, what is the right way to do a "insert on duplicate key update" sort of thing?

Right now I'm doing something like

$user = User::find( array( 'conditions' => 'user_id = ?', $userId ) );

if( !empty( $user->games ) {
    $user->games->game_data = 'some data';
}
else {
    $user->create_games( array( 'game_data' => 'some data' ) );
}

But I'm guessing that there might be a way to do this in one line ...