Search code examples
laravelmaatwebsite-excellaravel-excel

Import CSV file in laravel


I'm using maatwebsite/excel and I have CSV file including 1449 rows where I have value and parent title in each row. (here is sample of it)

screen1

what i want is to get id of parents from another table and use those id's instead of titles (which i have in my csv)

Codes

import function

public function importsku(Request $request) {
      Excel::load($request->file('file'), function($reader) {
        $results = $reader->all();

         foreach($results as $row){
            $findermap = new FinderMap;
            $findermap->ymm_value_id = $row->ymm_value_id;
            $findermap->sku = $row->sku;
            $findermap->save();
        }

        Session::flash('success', 'Your Data imported successfully.');
        return redirect()->route('finders.index');
      });
}

More info

The parents name that I'm looking to get their id's are stored in table named finder_ymm_values where their dropdown_id is 4 I think this will helps us to limit our search and get results faster

Question

What should I add to my import function in order to search for my parents name and get their id's for each value i have?

UPDATE

I added code below to my import function and now it does get the id's that i'm looking for, but the issue is it gets them in collection.

code i added

foreach($results as $row){
  //added
  $vals = FinderYmmValue::where('title', $row->ymm_value_id)->where('dropdown_id', '4')->pluck('id');
  $findermap = new FinderMap;
  $findermap->ymm_value_id = $vals; //changed
  $findermap->sku = $row->sku;
  $findermap->save();
}

error i get

SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails .......... insert into finder_maps (ymm_value_id, sku, updated_at, created_at) values ([303], L0R88AA, 2018-06-14 10:41:51, 2018-06-14 10:41:51))

As you can see in last line of my error i get my id as [303]

any idea?


Solution

  • SOLVED

    here last changes I've made and imported my file successfully.

    foreach($results as $row){
      $vals = FinderYmmValue::where('title', $row->ymm_value_id)->where('dropdown_id', '4')->pluck('id');
      foreach ($vals as $val) {
        $valid = $val;
      }
      $findermap = new FinderMap;
      $findermap->ymm_value_id = $valid;
      $findermap->sku = $row->sku;
      $findermap->save();
    }
    

    hope it can help others.