【问题标题】:How to bulk import user data which also has a profiles table in laravel using Maat maatwebsite/excel package?如何使用 Maat maatwebsite/excel 包批量导入在 laravel 中也有配置文件表的用户数据?
【发布时间】:2019-06-25 17:30:07
【问题描述】:

我有一个模型用户,它与模型配置文件具有一对一的关系。

profile 表有两列 user_id integer column 和 'information' jsonb column。我有一个 csv 文件,其中包含一个用户列表,其中包含他们的名称 id 、信息等等。我想要的是将 csv 文件中的信息存储到我的用户表和配置文件表中。

我能够将信息存储在用户表中。但无法将用户配置文件信息存储在配置文件表 json 列中。

这是我将数据从控制器传递到 excel 的方式

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

        return back();
    }

这是 UsersImport 类代码

class UsersImport implements ToModel
{

    public function model(array $row)
    {
        return new User ([
            'student_id' => $row[0],
            'name' => $row[1],
            'email' => $row[2],
            'password' => '123456'


        ]);

    }

}

用户表:

Schema::create('users', function (Blueprint $table) {
            $table->increments('id');
            $table->string('name');
            $table->string('email')->unique();
            $table->string('student_id')->unique();
            $table->timestamp('email_verified_at')->nullable();
            $table->string('password');
            $table->rememberToken();
            $table->timestamps();
        });

个人资料表:

Schema::create('profiles', function (Blueprint $table) {
            $table->increments('id');
            $table->integer('user_id');
            $table->jsonb('information')->nullable();
            $table->timestamps();
        });

【问题讨论】:

标签: excel laravel import maatwebsite-excel


【解决方案1】:

//用User::Create替换新用户

class UsersImport implements ToModel
{

    public function model(array $row)
    {
        $user = User::create([
            'student_id' => $row[0],
            'name' => $row[1],
            'email' => $row[2],
            'password' => '123456'


        ]);

      $user_id = $user->id;
      return $user;    
    }

}

【讨论】:

    【解决方案2】:

    试试这个,可能有用

    class UsersImport implements ToModel
    {
    
        public function model(array $row)
        {
            $user = new User ([
                'student_id' => $row[0],
                'name' => $row[1],
                'email' => $row[2],
                'password' => '123456'
            ]);
    
            //create a profile for user, I'm assuming that you have model Profile for profiles table
            Profile::create([
                'user_id' => $user->id,
                //and other profile data    
            ]);  
            return $user;
    
        }
    
    }
    

    【讨论】:

      猜你喜欢
      • 2021-10-08
      • 2021-12-22
      • 2020-07-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多