Love Fuel?    Donate

FuelPHP Forums

Ask your question about FuelPHP in the appropriate forum, or help others by answering their questions.
error when deleting from table with dual primary key
  • I'm getting a "Primary key cannot be changed" exception when I try to delete a record from a table that has a dual primary key. Hopefully I'm just doing something wrong - any help is much appreciated! Here's the full story : I've got three tables/models - users, tokens, and user_tokens. Users and tokens have many user_tokens, and user_tokens belong to users and tokens. (Can't just establish a many-to-many between users and tokens because I'm storing created_at as well in the user_tokens table.) The primary keys for user_tokens is user_id and token_id. And like I said, I cannot seem to delete records from user_tokens. I get the "primary key cannot be changed" error. Here's the ORM definitions : In Model_User :
    protected static $_has_many = array(
      'tokens' => array( 
        'model_to' => 'Model_User_Token',
        'cascade_delete' => true  
      )
    );
    

    In Model_User_Token :
    protected static $_primary_key = array( 'user_id', 'token_id');
    
    protected static $_belongs_to = array(
      'user',
      'token'
    );
    

    In Model_Token :
    protected static $_has_many = array(
      'users' => array(
        'model_to' => 'Model_User_Token'
      )
    );
    

    And here's how I'm testing deleting from user_tokens :
    $tokens = $user->tokens;
    
    foreach( $tokens as $t )
      $t->delete();
    

    Any help is much appreciated!
  • As noted in the docs primary keys shouldn't be used as foreign keys as you are doing in your Model_User_Token.
  • Ah right.. Ok, fair enough. Thanks very much Jelmer! I think I was confused because originally there was a many-to-many relationship between users and tokens, and in that case having the dual primary key in user_tokens was exactly what was needed. When my team decided to store created_at in the user_tokens table, the many-to-many relationship became a has-many/belongs-to relationship. In case it helps anyone, my solution was simply to add an id column as the primary key and then set a unique index for user_id and token_id. (A user can only receive each token once...)

Howdy, Stranger!

It looks like you're new here. If you want to get involved, click one of these buttons!

In this Discussion