使用 Laravel Excel to Collection 插入不正确的表名

问题描述

我正在尝试使用 Laravel Excel 关注 ToCollection 插入关系数据

use Maatwebsite\Excel\Concerns\ToCollection;

但是查询试图插入表 objective_years 而不是 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],]);
        }
    }
}

我有两个具有多对多关系支点的模型。

目标

class Objective extends Model
{
    use HasFactory;

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

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

}

年份

class Year extends Model
{
    use HasFactory;

    protected $fillable = [
        'name'
    ];

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

目标年

class ObjectiveYear extends Model
{
    use HasFactory;

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

控制器

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!');
  }
}

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)