简体   繁体   中英

How can I join two tables and import the data by excel using Maatwebsite package in laravel?

i am trying two join User and Clients table by using query in controller

Export function in Controller

 public function export() 
    {
        //$arrays = [$level_one_array, $level_two_array, $level_three_array];
        $arrays =  Client::select('clients.*','users.*')->join('users', 'users.id', '=', 'clients.user_id')->where('users.type', '=', 'client')->get();
        return Excel::download(new ClientsExport($arrays), 'clients.xlsx');
    }

Users and clients tables are joined by id. I am passing this filtered data to export function

code inside ClientsExport

class ClientsExport implements FromCollection
{
    /**
    * @return \Illuminate\Support\Collection
    */

    private $collection;

    public function __construct($arrays)
    {
        $output = [];

        foreach ($arrays as $array) {
            // get headers for current dataset
            $output[] = array_keys($array[0]);
            // store values for each row
            foreach ($array as $row) {
                $output[] = array_values($row);
            }
            // add an empty row before the next dataset
            $output[] = [''];
        }

        $this->collection = collect($output);
    }

    public function collection()
    {
        return $this->collection;
    }
}

but I am getting error

[2021-11-09 14:42:58] local.ERROR: array_values() expects parameter 1 to be array, object given {"userId":1,"exception":"[object] (ErrorException(code: 0): array_values() expects parameter 1 to be array, object given at /home/myonecity/public_html/crm/app/Exports/ClientsExport.php:23)
[stacktrace]

How to fix this issue?

Make the following changes in your export function. Replace get() with toArray().

public function export() 
{
    //$arrays = [$level_one_array, $level_two_array, $level_three_array];
    $arrays =  Client::select('clients.*','users.*')->join('users', 'users.id', '=', 'clients.user_id')->where('users.type', '=', 'client')->toArray();
    return Excel::download(new ClientsExport($arrays), 'clients.xlsx');
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM