FriendsOfCake / cakephp-csvview

CakePHP: A view class for generating CSV
MIT License
176 stars 64 forks source link

Export data from query with related table #131

Open nicocins opened 3 years ago

nicocins commented 3 years ago

Dear all,

I have an issue when I export data with csvview.

I want to export data from two associated table :

$this->response = $this->response->withDownload(‘Inventaire.csv’);
$this->loadModel(‘Details’);
$details = $this->Details->find(‘all’)->contain([‘Scans’])
->where([‘Scans.idInventory’ => $idInventory]);

$details->select([‘Scans.nb_elements’, ‘Details.ean’, ‘Details.qty’]);
$this->set(compact(‘details’));
$this->viewBuilder()
->setClassName(‘CsvView.Csv’)
->setOptions([
‘serialize’ => ‘details’,
‘delimiter’ => ‘;’,
‘enclosure’ => ‘’,
‘bom’ => true
]);

When I export data from only one table (Details) it works, but when I add “Scans” table I got this message:

Notice (8): Array to string conversion [ ROOT\vendor\friendsofcake\cakephp-csvview\src\View\CsvView.php , line 333 ]

It’s like he s trying to display an array instead of my field Scans.nb_elements.

I check my variable $details and everything is ok.

Could you help me about this ?

Thanks in advance.

oresch commented 3 years ago

Hi @nicocins ,

I was faced with the same issue and found the following solution. Assuming you have Devices and DeviceStatuses tables. The following did help me:

$data = $this->Devices->find()
                ->select([
                    'Devices.id', 'Devices.name', 'Devices.ip_address',
                    'status' => 'DeviceStatuses.name'
                ])
                ->contain([                   
                    'DeviceStatuses'
                ]);

With 'status' => 'DeviceStatuses.name'I was finally able to use the depending information and export it to csv.

And in the $_extract array I put the following - as already mentioned in the doc:

$_extract = [
                'Devices.id',
                'Devices.name',
                'Devices.ip_address',
                function (array $row) {
                    return $row['name'];
                },

Hope this helps

nicocins commented 3 years ago

Thanks for your help ! i ll try !

tgoeminne commented 2 years ago

It used to work in the older version, why is not working in this one? Need to update plugin so can work with associated models again.

dereuromark commented 1 year ago

We should add a note into the docs here I guess.