【问题标题】:Laravel import Seller_id from Excel FileLaravel 从 Excel 文件中导入 Seller_id
【发布时间】:2020-06-22 20:01:12
【问题描述】:

我正在构建多商店平台,所以我可以从管理面板管理商店的产品

我正在使用this package 将产品从 excel 文件导入到特定的 Shop,并且我在 Products Table 中有 Shop_id

现在,我可以成功地将 excel 文件导入数据库。但是,问题是为每个产品分配 Shop_id

有什么想法吗?

PruductImport.php

public function model(array $row)
    {
        return new Product([
            'name'         => $row['Name'],
            'price'        => $row['Price'],
        ]);
    } 

控制器

public function import(Request $request)
    {
        Excel::import(new PruductImport,request()->file('file'));

        return back()->with('success','Done!');
    }

【问题讨论】:

    标签: php mysql laravel twitter-bootstrap laravel-5


    【解决方案1】:
    class ProductImport ...
    {
        protected $shop_id;
    
        public function __construct($shop_id)
        {
            $this->shop_id = $shop_id;
        }
    
        public function model(array $row)
        {
            return new Product([
                'name'         => $row['Name'],
                'price'        => $row['Price'],
                'shop_id'      => $this->shop_id,
            ]);
        } 
    }
    
    /// how to create a new instance and pass the shop id
    
    new ProductImport($shop_id)
    
    // in the Controller
    
    Excel::import(new PruductImport($shop_id), request()->file('file'));
    

    【讨论】:

    • 控制器有什么改变吗?导致这不起作用
    • 是的,上面的最后一行...您必须将商店 ID 传递给您正在创建的 ProductImport 的新实例,因为您刚刚将其添加到构造函数中以便以后可以使用它
    • 我认为我做错了,请给我一个完整的控制器代码示例
    • 它现在显示这个错误 SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint failed
    • 现在您正在处理数据库上的外键约束...所使用的shop_id 必须存在于数据库中
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-03-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-07-11
    相关资源
    最近更新 更多