0

我想将excel文件中的数据插入数据库。从 excel 文件导入行时,它还将插入值表单输入字段。假设我有一个价格输入。和excel文件的输入字段。Excel 文件包含 100 行。所以当导入这个时,每一行都会插入价格文本。

刀片文件:

<input type="text" name="price" />
<input type="file" name="bulk_file" />

控制器:

 public function bulk_upload(Request $request)
{
    if($request->hasFile('bulk_file')){
        $import = new ProductsImport;
        Excel::import($import, request()->file('bulk_file'));
    }
    return back();
}

模型:

    class ProductsImport implements ToCollection, WithHeadingRow, WithValidation, ToModel
   {
    private $rows = 0;
    public function collection(Collection $rows) {
        $canImport = true;
        if($canImport) {
            foreach ($rows as $row) {
                $productId = Product::create([
                            'name' => $row['name'],
                            'added_by' => Auth::user()->user_type == 'seller' ? 'seller' : 'admin',
                            'user_id' => Auth::user()->user_type == 'seller' ? Auth::user()->id : User::where('user_type', 'admin')->first()->id,
                            'category_id' => 24,
                            'brand_id' => !empty($row['brand_id']) ? $row['brand_id']: 0,
                            'price' => request('price');
                ]);
            }

            flash(translate('Products imported successfully'))->success();
        }

    }

我正在使用 maatwebsite/excel 包。你能帮我修改我的代码吗?

4

1 回答 1

0

通过将价格传递给 ProductsImport 类进行修改:

    class ProductsImport implements ToCollection, WithHeadingRow, WithValidation, ToModel
   {
    protected $price;

    function __construct($price) {
        $this->price = $price;
    }
    private $rows = 0;
    public function collection(Collection $rows) {
        $canImport = true;
        if($canImport) {
            foreach ($rows as $row) {
                $productId = Product::create([
                            'name' => $row['name'],
                            'added_by' => Auth::user()->user_type == 'seller' ? 'seller' : 'admin',
                            'user_id' => Auth::user()->user_type == 'seller' ? Auth::user()->id : User::where('user_type', 'admin')->first()->id,
                            'category_id' => 24,
                            'brand_id' => !empty($row['brand_id']) ? $row['brand_id']: 0,
                            'price' => $this->price
                ]);
            }

            flash(translate('Products imported successfully'))->success();
        }

    }

在控制器中:

public function bulk_upload(Request $request)
{
    if($request->hasFile('bulk_file')){
        $import = new ProductsImport($request->price);
        Excel::import($import, request()->file('bulk_file'));
    }
    return back();
}
于 2021-11-18T21:59:42.833 回答