laravel - 在用户使用 Laravel Excel 导入之前创建配置文件模型
问题描述
我正在使用 Laravel Excel 包通过 Excel 导入我的用户 我想在导入用户之前创建一个配置文件模型。我该怎么做呢?用户表与配置文件表具有 1:1 的关系。这意味着每个用户都有一个配置文件
用户表:
id username password is-admin created_at updated_at department_id
1 4480115617 $2y$10$HUBeOzDlTvaJKmI8d5GXJ.qzbqsDcDooi4WG0BrOAHOE9Ce3HMgC6 1 2021-04-16 10:07:34 2021-06-24 04:51:18 10
52 4480124152 $2y$10$.hOMGBCdcrBNx6UbQ4vAOeInnma6mjnztRxL2k8kpV/vK2dEWrj8O 0 2021-07-08 08:01:07 2021-07-08 08:01:07 1
53 12345678910 $2y$10$5d.FMSRyf/KT8bOtQYaSA.BZMLVEKFgjiXL/pjfHCMXmZ7tbZgnPW 1 2021-07-08 08:02:07 2021-07-08 08:02:07 2
54 4420827661 $2y$10$TE8biYPPHhv7ZdUfmY11sO9.7QXOaqKAyWkOEbgsBxJi2uq2iLFs2 1 2021-07-13 06:50:38 2021-07-13 06:50:38 3
简介表:
id user_id avatar_src phone address email created_at updated_at field_id name family father national_code
6 1 users/avatars/default.jpg 0xxxxxxxxxxx یزد aa@asdag.com (NULL) 2021-06-24 04:51:18 (NULL) محمد غریب
21 52 users/avatars/52.jpg 09134576502 adasdasdasdasdas mohamm@taho.com 2021-07-08 08:01:08 2021-07-13 06:54:05 (NULL) محمد کریمی
22 53 users/avatars/default.jpg 09134575052 daasdasd asda@yaho.com 2021-07-08 08:02:07 2021-07-08 08:02:07 (NULL) مسعود رامینی
23 54 users/avatars/default.jpg 09134576502 قلثقلقثقثقثث reza@yaho.com 2021-07-13 06:50:38 2021-07-13 06:50:38 (NULL) مهدی رضایی
解决方案
假设您使用的是自定义导入类,如果不是,很多人希望通过创建一个在文档中定义的名为UsersImport
in的新类来使用自定义导入类。app/Imports
用户导入.php
namespace App\Imports;
use App\User;
use Illuminate\Support\Collection;
use Maatwebsite\Excel\Concerns\ToCollection;
class UsersImport implements ToCollection
{
public function collection(Collection $rows)
{
foreach ($rows as $row)
{
// We are creating an instance to use it to create the profile
$user = User::create([
'username' => $row[0], //or name of the col with $row['username']
'password' => $row[1],
'is-admin' => $row[2],
'department_id' => $row[3]
]);
// create the profile using $user and one-to-one relationship
// assuming your relationship is profile() defined in User Model
$user->profile()->create([
'avatar_src' => $row['avatar_src'],
'phone' => $row['phone'],
//... your other columns
]);
}
}
}
接下来在 Database Seeder 中调用您的方法 Excel::import(new UsersImport, storage_path('Pathtolfile.xlsx'));
推荐阅读
- bash - 需要将局部变量加载到 Bash 中的关联数组中
- visual-studio - 在 Visual Studio 2017 中创建 CMake Qt 项目
- bash - 使用管道和重定向解析输入字符串
- python - python cProfile/snakeviz 无法处理调用同一函数的多个函数
- javascript - 将 JavaScript 日期转换为格式化字符串
- android - 使用简单日期格式解析日期时出现空指针异常
- mysql - 为什么它会在mysql中引发语法错误
- python - 使用 python / requests 表单处理 google recaptcha
- spring-boot - 在没有模拟的情况下测试 REST API 提供程序响应
- django - 将 Django 用户与另一个用户相关联