Can a model have multiple tables in CakePHP?

前端 未结 5 746
伪装坚强ぢ
伪装坚强ぢ 2021-01-05 13:18

Can a model have multiple tables in CakePHP?

5条回答
  •  情歌与酒
    2021-01-05 13:55

    I guess you want to implement some sort of inheritance in the database (that requires to join the data stored in the parent table when retrieving information from the child table). My approach to solve this was using afterFind callback in the child model. I redefined the callback as follows:

    function afterFind($results) {
        foreach ($results as $key => $val) {
                    $fieldRetrieved=$this->query("SELECT *field* FROM *parent_table* WHERE id={$val['*ChildModelName*']['id']}");
                    $results[$key]['*ChildModelName*']['*field*']=$fieldRetrieved[0]['*parent_table*']['*field*'];
        }
        return $results;
    }
    

    In this way I was including the field/s from the parent table to the results obtained from the child table. In this case I've assumed that both tables are index with a field called id and that field, in the child table, is also a foreign key to the parent table (thus creating the pseudo-inheritance).

提交回复
热议问题