【问题标题】:How to pass user_id for importing excel using Laravel?如何通过 user_id 使用 Laravel 导入 excel?
【发布时间】:2021-03-10 05:40:47
【问题描述】:

我在使用 Laravel 导入 excel 时遇到问题。 用户希望将供应商数据的excel导入数据库。 suppliers 表得到了user_id,但用户可能没有自己的user_id。因此,在导入 excel 文件时,用户使用没有 user_id 列的 excel。 所以我想传递该用户的user_id 并存储在数据库中。

供应商进口控制器

public function store(Request $request)
{
    $user_id = auth()->user()->id;        
    Excel::import(new SuppliersImport($user_id), request()->file('file'));

    return  redirect('/suppliers')->withStatus('Excel file imported successfully');
}

供应商进口

public function  __construct($user_id)
{

    $this->user_id =$user_id;
}
public function model(array $row)
{
    return new Supplier([
        'name' =>$row[0],
        'phone' =>$row[1],
        'email' =>$row[2],
        'address' =>$row[3],
        'city' =>$row[4],
        'country' =>$row[5],
        'customer' =>$row[6],
        'user_id'=> $this->user_id,         
        
    ]);

错误

SQLSTATE[HY000]: 一般错误: 1364 Field 'user_id' doesn't have a default value (SQL: insert into suppliers (name, phone, email, address, @987654333 @, country, customer, updated_at, created_at) 值 (soe, 176893848, soe@mail.com, abc, Yangon, Myanmar, 1, 2020-11-27 12:15:08, 2020 -11-27 12:15:08))

【问题讨论】:

  • Welcome to SO ... user_id 在模型上设置为“可填充”吗,供应商?
  • 不。我会这样做的。

标签: laravel excel-import


【解决方案1】:

所以你可以做的是

public function model(array $row)
{    
    $user = auth()->user();  //Get the current user 
    return new Supplier([
        'name' =>$row[0],
        'phone' =>$row[1],
        'email' =>$row[2],
        'address' =>$row[3],
        'city' =>$row[4],
        'country' =>$row[5],
        'customer' =>$row[6],
        'user_id'=> $user->id,      // add their user id when importing    
        
    ]);

【讨论】:

    猜你喜欢
    • 2020-07-09
    • 1970-01-01
    • 1970-01-01
    • 2011-02-28
    • 1970-01-01
    • 1970-01-01
    • 2021-12-22
    • 2019-07-23
    • 2019-03-10
    相关资源
    最近更新 更多