如何解决使用 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 举报,一经查实,本站将立刻删除。