tags:

views:

1485

answers:

6

How does CakePHP deal with tables that don't have an id column?

I'm trying to save some relationship data, but Cake wants to "SELECT LAST_INSERT_ID()", however the table that it's trying to save to does not have the id column so the id is for a different table.

Specifically, I've got tables for "Games" and "Players", and a relationship table called "game_players". game_players has the fields game_id and player_id, and it's on this table that I can't save the relationship data.

To clarify: it's the game_player table that's causing the problem. This table does not have, nor should it have, an id field. It's only storing relationships between player and game, and the primary key is (game_id, player_id)

How does CakePHP handle this situation/relationship?

A: 

As a matter of your time and effort, would it be better to just go ahead and add the id field? You may eventually expand the needs of this table in ways you hadn't expected.

Just a suggestion.

jerebear
+2  A: 

CakePHP does not support composite primary keys. Add a primary key called 'id' to your game_players table. Model-and-Database-Conventions

Leigh Mackay
+4  A: 

Does Game HABTM Player, or vice versa? If so, you should not have an ID field on your join table games_players. And you should be able to save data to it by calling save on Game with a data array like

$this->Game->save(array(
  'Player'=>array(
    'Player'=>array(
      1,4,5,9 // Player IDs
    )
  )
));

In this case, Cake will not try and get the last insert id.

If however, Game does not HABTM Player, and you are calling save on your model GamePlayer directly, it should have an ID field to fit with Cake conventions.

neilcrookes
A: 

In the normal course of things your join table should actually be called games_players not game_players - if the table is called game_players then you would need to tell Cake this in your respective model files.

If it is just a join table then it shouldn't ordinarily need an id field. There are circumstances where you will want to add id (or other fields) to your join table but you don't have to.

John
A: 

As others have mentioned, your table should be called games_players and you should never use it directly (cake takes care of that automagically). You must setup your relations between Game and Player models, and let the cake take care of the rest.

dr Hannibal Lecter
A: 

var $primaryKey = 'example_id'; $primaryKey is what do you looking for.