Search code examples
cakephpforeign-keyscakephp-2.0model-associations

Cakephp 2.3: Build model associations when foreign keys do not match model columns


How, generally, can I create foreign keys (ie. columns) in one table that Cakephp associates, by different names, with columns of another model? Incidentally, I am using bake all to get started with the standard CRUD set up.

The general form of my question is:

Table_A has id|label|TableB_labelA_id|TableB_labelB_id

Table_B has id|label

To make the rest of the question less ugly, though, this is my current application:

games has id|date|us|them

teams has id|name

I assume this can be achieved through aliases, and association definitions alone, but I don't quite get how. It also occurred to me to simply create Us and Them models that extend Team, but this seemed an undue effort.

I've also noticed, in my Game model that Us and Them are listed in the $belongsTo array, instead of $hasMany which would intuitively have seemed more correct.

Ideas? I'd be most appreciative!


Solution

  • You are right about only needing alias and proper association definitions. Here's what you neeed.

    class Game extends AppModel {
        public $belongsTo = array(
            'Us' => array(
                'className' => 'Team',
                'foreignKey' => 'us'
            ),
            'Them' => array(
                'className' => 'Team',
                'foreignKey' => 'them'
            ),
        );  
    }
    

    Bake wouldn't be able to help you with this. It can only make it's educated guesses if all naming is as per convention and in this case that's not possible.