Background: CakePHP 2.6.3. A pretty stable app. New behavior (MyCustomBehavior
) created to output some extra info.
I have a Model MyModel
acting as Containable
(defined in AppModel
) and then MyCustom
(defined in MyModel
). MyCustomBehavior
is written in a way that it needs to work with the Model's associations with other Models in my app.
Problem: Whenever I contain related models in my find()
call of MyModel
, I cannot get a complete list of MyModel
associations because Containable
behavior unbinds the models that are not contained. However, if I don't set contain
in my find()
options or set 'contain' => false
everything works as expected.
Sample MyModel->belongsTo
public $belongsTo = array(
'MyAnotherModel' => array(
'className' => 'MyAnotherModel',
'foreignKey' => 'my_another_model_id',
'conditions' => '',
'fields' => '',
'order' => ''
),
'Creator' => array(
'className' => 'User',
'foreignKey' => 'user_id',
'conditions' => '',
'fields' => '',
'order' => ''
),
'Approver' => array(
'className' => 'User',
'foreignKey' => 'approver_id',
'conditions' => '',
'fields' => '',
'order' => ''
),
'Status' => array(
'className' => 'Status',
'foreignKey' => 'status_id',
'conditions' => '',
'fields' => '',
'order' => ''
),
);
Sample find()
$this->MyModel->find('all', array(
'fields' => array(...),
'conditions' => array(...),
'contain' => array('Approver', 'Status')
));
Result of MyModel->belongsTo
in MyCustomBehavior::beforeFind()
$belongsTo = array(
'Approver' => array(
...
),
'Status' => array(
...
),
);
Expected MyModel->belongsTo
in MyCustomBehavior::beforeFind()
$belongsTo = array(
'MyAnotherModel' => array(
...
),
'Creator' => array(
...
),
'Approver' => array(
...
),
'Status' => array(
...
),
);
Obvious solution: One dumb way to solve the problem is to simply set Containable
behavior in MyModel
instead of AppModel
to control the order of loading the behaviors, i.e., public $actsAs = ['MyCustom', 'Containable']
. This solution is not the best because there may be other behaviors in other models that depend on Containable
, so the order of Containable
needs to set in each model in app explicitly and hope that I didn't break the app somewhere.
A similar(related) question was asked on SO here but has no answers.
Need a more robust solution that can address the needs of MyCustomBehavior
without having to make changes in rest of the app and looking out for any unexpected behavior.