In Cakephp associations, how do you change the relationship key?

Asked

Viewed 131 times

1

In Cakephp associations by default it always does the relationship being the model name in the singular followed by _id, i.e., model_id.

It is possible to change this relationship key to another field of the table?

I tried to use foreignKey but it didn’t work.

Below the two models:

<?php
class Cart_item extends AppModel 
{
    public $name = 'Cart_item';         
}
?>

And Cart:

<?php
class Cart extends AppModel 
{
    public $name = 'Cart';      
    public $hasMany = array(
            'Cart_item' => array(
                'className' => 'Cart_item',
                'foreignKey' => 'Cart_uid'
            )
        );      
}
?>
  • 1

    foreignKey should work. This is the way to do it. Put your code to see if there is no other mistake

2 answers

1

Make sure you’re not confusing what should appear on foreignKey. As the cake manual shows, the model should look like this:

class Profile extends AppModel {
    public $belongsTo = array(
        'User' => array(
            'className' => 'User',
            'foreignKey' => 'user_id'
        )
    );
}

0

Maybe there’s a mistake on the line

 'foreignKey' => 'Cart_uid',

Possibly would be

'foreignKey' => 'Cart_id',

Browser other questions tagged

You are not signed in. Login or sign up in order to post.