简体   繁体   中英

How to get Laravel last inserted ID from Excel import sheet

I'm relatively new to Laravel (historically I've written all my PHP from scratch) just trying to learn the basics Laravel site creation before making a new real site. Right now I have a multi-sheet excel file that I want to import and place the data into tables. I followed the Laravel Excel instructions and I have this ChartImport.php file that works well exactly as written/expected.

<?php

namespace App\Imports;

use App\Chart;
use App\Chart_count;
use Maatwebsite\Excel\Concerns\ToModel;
use Maatwebsite\Excel\Concerns\WithMultipleSheets;

class ChartImport implements WithMultipleSheets
{

    public function sheets(): array
    {
        return [
            0 => new ChartNameImport(),
            1 => new ChartCountImport(),
        ];
    }
}

class ChartNameImport implements ToModel
{
    /**
    * @param array $row
    *
    * @return \Illuminate\Database\Eloquent\Model|null
    */
    public function model(array $row)
    {
        return new Chart([
            'title' => $row[0],
            'owner_id' => auth()->id()
        ]);
    }
}


class ChartCountImport implements ToModel
{
    /**
    * @param array $row
    *
    * @return \Illuminate\Database\Eloquent\Model|null
    */
    public function model(array $row)
    {
        return new Chart_count([
            'chart_id' => 3,
            'count' => $row[0],
            'name' => $row[1],
        ]);
    }
}

Though right now, as you can see, I'm hardcoding

            'chart_id' => 3

I want the chart_id to be the automatically created id of the previous function call, but I'm not sure if there's any Laravel way to go about it. I'm sure I could probably create a new PDO instance and grab the data from the database or something, but that doesn't seem like a good way at all. How would you go about doing it? Thanks!

Instead of importing to models you can import to collections :

example:

namespace App\Imports;

use App\User;
use Illuminate\Support\Collection;
use Maatwebsite\Excel\Concerns\ToCollection;

class UsersImport implements ToCollection
{
    public function collection(Collection $rows)
    {
        foreach ($rows as $row) 
        {
            $id = DB::table('users')->insertGetId([
                'title' => $row[0],
                'owner_id' => auth()->id()
            ]);
        }
    }
}

notice i am using the [insertGetId] method to insert a record and then retrieve the ID.

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