In associations in CakePHP, how to change the relationship key?

1

In associations in CakePHP by default it always makes the relationship being the model name in the singular followed by _id, that is, model_id.

Is it possible to change this relationship key to another table field?

I tried to use foreignKey but it did not work.

Below the two models:

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

E Cart:

<?php
class Cart extends AppModel 
{
    public $name = 'Cart';      
    public $hasMany = array(
            'Cart_item' => array(
                'className' => 'Cart_item',
                'foreignKey' => 'Cart_uid'
            )
        );      
}
?>
    
asked by anonymous 04.02.2014 / 18:56

2 answers

1

Make sure you are not confusing what should appear in the 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'
        )
    );
}
    
05.02.2014 / 14:12
0

There may be a line error

 'foreignKey' => 'Cart_uid',

Possibly it would be

'foreignKey' => 'Cart_id',
    
13.02.2015 / 17:18