Master/Detail find

From CTRNet Wiki
Jump to: navigation, search

Running find on a master model requires a bit of gymnastic. The concept of master detail is that a given master table can have many detail ones. That doesn't quite fit in CakePHP as you have to declare your relations in hasOne and you can only have one relation link under ModelDetail. That's where the magic comes in.

Retrieving details

You run a plain find query on a master model. You expect to see the details attached to the results. That's being done in MasterDetailBehavior::afterFind. It reads all the results rows and fetch the detail data to attach it to the result.

Clauses based on details

This one is a bit trickier. You run a find on a specific master control id and you have clauses based on details. It cannot basically work because the details informations are only retrieved after the master results are fetched. MasterDetailBehavior::beforeFind handles that if the query respects one condition. There must be a condition made on {model_name}Master.{model_name}_control_id. Then, the required detail table name is fetched and the master model is recreated with a new hasOne relationship based directly on that detail table. Then, when the original query is executed, all parameters based on the detail table are accepted as its now being associated properly.

Important: The detail table name need to respect cakephp naming convention. Becaused it's being linked on the fly, having a custom name will not work.

Note: For the query, the model is temporarily replaced with the one generated by beforeFind. The original model is then restored in afterFind to ensure any models variables are not lost in the process.

Personal tools