CakePHP belongsTo relationship with a variable 'model' field.
Posted
by gomezuk
on Stack Overflow
See other posts from Stack Overflow
or by gomezuk
Published on 2010-03-11T13:51:22Z
Indexed on
2010/03/11
17:29 UTC
Read the original article
Hit count: 392
I've got a problem with a belongsTo relationship in CakePHP.
I've got an "Action" model that uses the "actions" table and belongs to one of two other models, either "Transaction" or "Tag". The idea being that whenever a user completes a transaction or adds a tag, the action model is created to keep a log of it. I've got that part working, whenever a Transaction or Tag is saved, the aftersave() method also adds an Action record. The problem comes when I try to do a find('all') on the Action model, the related Transaction or Tag record is not being returned.
actions: id model model_id created
I thought I could use the "conditions" parameter in the belongsTo relationship like this:
<?php
class Action extends AppModel {
var $name = 'Action';
var $actsAs = array('Containable');
var $belongsTo = array(
'Transaction' => array(
'foreignKey' => 'model_id',
'conditions' => array("Action.model"=>"Transaction")
),
'User' => array(
'fields' => array('User.username')
),
'Recommendation' => array(
'conditions' => array("Action.model"=>"Recommendation"),
'foreignKey' => 'model_id'
)
);
}
?>
But that doesn't work.
Am I missing something here, are my relationships wrong (I suspect so)? After Googling this problem I cam across something called Polymorphic Behaviour but I'm not sure this will help me.
© Stack Overflow or respective owner