tags:

views:

37

answers:

3

Hi all,

I got a table with a few columns.
The table has a primary key (replyid), and two foreigne keys (userid and postid).

Here is the structure of the table: {replyid, content, userid, postid}

The Reply table got two foreigne keys.
I am not sure if this is a correct to set the foreign keys like this:

class Post extends AppModel{   
    var $name = 'Post';
    var $useTable = 'post';
    var $primaryKey = 'postid';
    var $belongsTo = 'User';
    var $hasMany = array(
        'Reply' => array(
            'className'     => 'Reply',
            'foreignKey'    => 'postid',          
            'foreignKey'    => 'userid'     
                        )
                        );  

                            }

?>

Could you helpplease?

+1  A: 

Unfortunately CakePHP does not support composite keys or partial primary keys. As recommended by the CakePHP manual, you can either use direct query calls such as:

CREATE TABLE posts_tags (
  id INT(10) NOT NULL AUTO_INCREMENT,
  post_id INT(10) NOT NULL,
  tag_id INT(10) NOT NULL,
  PRIMARY KEY(id)); 

...Or, you can create a surrogate key, perhaps an auto-increment value. Rather than using an auto-increment key as the primary key, you may also use char(36). CakePHP will then use a unique 36 character uuid (String::uuid) whenever you save a new record using the Model::save method. (From CakePHP Manual)

KahWee Teng
+1  A: 

Two foreign keys are fine,but you should define the relationshions in right models.

In your post model,

var $hasMany = array( 
    'Reply' => array( 
        'className'     => 'Reply', 
        'foreignKey'    => 'postid',           
        //'foreignKey'    => 'userid'
                    ) 
                    );   

In your user model,

var $hasMany = array( 
    'Reply' => array( 
        'className'     => 'Reply', 
        //'foreignKey'    => 'postid',            
        'foreignKey'    => 'userid'      
                    ) 
                    );   
SpawnCxy
Multiple foreign keys, as SpawnCxy says, are fine - and often the norm. I would stick to Cake convention and name them like post_id, user_id.
Leo
+1  A: 

The manual is pretty good on this: http://book.cakephp.org/view/78/Associations-Linking-Models-Together.

If you're still confused, build your tables in the database and use cake bake to build the models - this way you'll see how Cake handles it natively. As I said earlier, though, I recommend that you name your db columns like foreign_id. It'll make life a lot easier.

Leo