Overriding CakePHP conventions. One table with 2 columns of the same model

285 views Asked by At

Suppose I have a table/model Products. Suppose I have a table/model Equivalencies which has among its columns this 2:

  • original_id
  • equivalent_id

Both original_id and equivalent_id have as foreign keys the primary key of Products. So, I can't follow the convention of naming original_id as product_id, because I also have to deal with equivalent_id (which would also be product_id).

What should I do?

Currently, I have the Product model configured as this:

public $hasMany = array(
    'Original' => array(
        'className' => 'Equivalency',
        'foreignKey' => 'original_id',
        'dependent' => false,
        'conditions' => '',
        'fields' => '',
        'order' => '',
        'limit' => '',
        'offset' => '',
        'exclusive' => '',
        'finderQuery' => '',
        'counterQuery' => '',
        'table' => 'products',
    ),
    'Equivalent' => array(
        'className' => 'Equivalency',
        'foreignKey' => 'equivalent_id',
        'dependent' => false,
        'conditions' => '',
        'fields' => '',
        'order' => '',
        'limit' => '',
        'offset' => '',
        'exclusive' => '',
        'finderQuery' => '',
        'counterQuery' => ''
    ),
);

Could anyone tell me if this is how it's supposed to be done?

What I Want I want to be able to find all the equivalencies of a given product, but with conditions over the relation (the one with original_id, equivalent_id). This doesn't work:

$original = $this->Product->find('all',
        array(
            'contain' => 'Product.Original.deleted_equivalent = false',
            'conditions' => array('Product.id' => $id)
        ));
1

There are 1 answers

0
Guillermo Mansilla On BEST ANSWER

Your model is fine, that's the way you should do it.

Your call to find is not.

Try this

$original = $this->Product->find('all',
    array(
        'contain' => array('Equivalent'),
        'conditions' => array('Product.id' => $id)
    ));