laravel - 如何通过 user_id 使用 Laravel 导入 excel?
问题描述
我在使用 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 字段 'user_id' 没有默认值 (SQL: 插入suppliers
( name
, phone
, email
, address
, city
, country
, customer
, updated_at
, created_at
) 值 (soe, 176893848, soe@mail.com, abc, Yangon , 缅甸, 1, 2020-11-27 12:15:08, 2020-11-27 12:15:08))
解决方案
所以你能做的是
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
]);
推荐阅读
- c# - 如何从代码后面访问数据到 MVVM
- r - 拆分或分离类“字符”的对象
- symfony - Chromedriver Centos 7 Headless
- python - 在分水岭opencv之后查找轮廓
- python - 如何在 Python 中使用队列进行线程处理时处理异常
- php - 继续重新生成一个新的 id 并检查数据库直到满足条件?
- python - Django REST Framework 验证错误:“输入有效的 URL。”
- python - Python 列表中的元素
- angular - Angular:NGX Bootstrap,预先输入的自定义模板查询突出显示
- c# - 平稳地将玩家推离物体