0

I'm attemptng to insert relational data using the Laravel Excel concern ToCollection

use Maatwebsite\Excel\Concerns\ToCollection;

however the query is attempting to insert into the table objective_years and not objective_year

ObjectivesImport.php

namespace App\Imports;
use App\Models\Objective;
use App\Models\ObjectiveYear;
use Illuminate\Support\Facades\Hash;
use Maatwebsite\Excel\Concerns\ToCollection;
use Illuminate\Support\Collection;


class ObjectivesImport implements ToCollection
{
    public function collection(Collection $rows)
    {

        foreach ($rows as $row)
        {

            $objectiveDetail =  Objective::create([
                  'description' => $row[0],
                  'guidance' => $row[1],
                  'team_id' => $row[2],
                  'subject_id' => $row[3],
            ]);

            $yearDetail =  ObjectiveYear::create([
                'objective_id' => $row[4],
                'year_id' => $row[5],

            ]);
        }
    }
}

I have two models with a many to many relatinship pivot.

Objective

class Objective extends Model
{
    use HasFactory;

    protected $fillable = [
        'description', 'guidance','subject_id','team_id'
    ];

    public function years ()
    {
      return $this->belongsToMany('App\Models\Year');
    }

}

Year

class Year extends Model
{
    use HasFactory;

    protected $fillable = [
        'name'
    ];

    public function objectives()
    {
        return $this->belongsToMany('App\Models\Objective')->withTimestamps();
    }
}

ObjectiveYear

class ObjectiveYear extends Model
{
    use HasFactory;

    protected $fillable = [
        'objective_id', 'year_id'
    ];
}

Controller

class ImportController extends Controller
{
  public function getImport()
  {
      return view('import');
  }

  public function import()
  {
      Excel::import(new ObjectivesImport, request()->file('csv_file'));
      return redirect('/')->with('success', 'All good!');
  }
}
cinameng
  • 313
  • 4
  • 14
  • 1
    please check your table name in database laravel add call table from database with plural name. if it is not plural than add this code in model define table name protected $table = 'my_flights'; – umefarooq Mar 03 '21 at 10:45
  • @umefarooq my db tables are named objectives, years and objective_year – cinameng Mar 03 '21 at 11:17
  • 1
    objectives and years are fine s per your model name, but you have to specify protected $table = 'objective_year'; in your Objective_Year Model as table name is not plural in database. – umefarooq Mar 03 '21 at 11:39
  • I see now thanks, I was to focussed on trying to understand why rather than just looking for a solution – cinameng Mar 03 '21 at 12:11

0 Answers0