在用户导入之前使用Laravel Excel创建配置文件模型



我正在使用Laravel Excel软件包通过Excel导入我的用户我想在导入用户之前创建一个概要模型。我该怎么做呢?用户表与概要表的关系为1:1。这意味着每个用户都有一个配置文件

User Table:

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

Profile Table:

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)  مهدی        رضایی                                

假设您正在使用自定义导入类,如果没有,您可能希望通过在文档中定义的app/Imports中创建一个名为UsersImport的新类来使用自定义导入类。

UsersImport.php

namespace AppImports;
use AppUser;
use IlluminateSupportCollection;
use MaatwebsiteExcelConcernsToCollection;
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
]);

}
}
}

接下来用Excel::import(new UsersImport, storage_path('Pathtolfile.xlsx'));调用数据库种子器中的方法