Export records with HABTM
dineshvasudev opened this issue · 1 comments
dineshvasudev commented
How can I export records associated with HABTM?
When I tried to export with help of csvview, it exports only one value but not all the associated values.
I have research programs containing various departments, I want to export the filtered search results as csv.
$this->loadModel('Researchprograms');
$this->loadModel('Departments');
$researchprograms = $this->Researchprograms->find('search', $this->Researchprograms->filterParams($this->request->query)) ->contain(['Users', 'Departments']);
foreach ($researchprograms as $researchprogram):
$data = [$researchprogram];
endforeach;
$_serialize = ['data'];
$this->response->download('my_file.csv');
$this->viewBuilder()->className('CsvView.Csv');
$this->set(compact('data','_serialize'));
This code generates csv file but every record has only one departments, but there are many departments for a record.
Let me know how can I export the records with all associated departments (HABTM)?
ADmad commented
Use a callable in $_extract
variable to format the departments list as required. For e.g.
$_extract = [
// other fields
'departments' => function ($row) {
return implode(',', Hash::extract($row, 'departments.{n}.name'))
}
];