Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to define two foreign keys in cakePHP

Tags:

cakephp

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?

like image 652
user327712 Avatar asked May 31 '26 18:05

user327712


1 Answers

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'      
                    ) 
                    );   
like image 174
Young Avatar answered Jun 02 '26 19:06

Young