首页 > 解决方案 > 如何从导入的 Excel 中批量附加数组数据的关系?拉拉维尔,PHP

问题描述

我终于可以将 excel 数据导入数据库(尽管与通常导入的代码不同),但它无法附加关系。

三张表:users(第一张表)、role_user(关系表)和角色(第二张表)

错误:在布尔值上调用成员函数角色() 错误的屏幕截图

用户导入.php

use App\User;
use Maatwebsite\Excel\Concerns\ToModel;

class UserImport implements ToModel
{
    /**
    * @param array $row
    *
    * @return \Illuminate\Database\Eloquent\Model|null
    */
    public function model(array $row)
    {
        return new User([
        'nisn' => $row[1],
        'name' => $row[2],
        'username' => $row[3],
        'email' => $row[4],
        'kelas' => $row[5],
        'jabatan' => $row[6],
        'tempat_lahir' => $row[7],
        'tgl_lahir' => $row[8],
        'bulan_lahir' => $row[9],
        'tahun_lahir' => $row[10],
        'jenis_kelamin' => $row[11],
        'agama' => $row[12],
        'tahun_masuk' => $row[13],
        'no_telp' => $row[14],
        'password' => $row[15],
        ]);
    }
}

AdminController.php(部分)

public function import_student(Request $request) 
    {
    $this->validate($request, [
        'file' => 'required|mimes:csv,xls,xlsx'
    ]);
    $import = Excel::toArray(new UserImport(), $request->file('file'));
        foreach($import[0] as $row) {
            //  dd($row[1].' '.$row[2]);
            $arr[] = [
                // If uncomment this id from here, remove [0] from foreach
                // 'id' => $row[0], 
                'nisn' => $row[1],
                'name' => $row[2],
                'username' => $row[3],
                'email' => $row[4],
                'kelas' => $row[5],
                'jabatan' => $row[6],
                'tempat_lahir' => $row[7],
                'tgl_lahir' => $row[8],
                'bulan_lahir' => $row[9],
                'tahun_lahir' => $row[10],
                'jenis_kelamin' => $row[11],
                'agama' => $row[12],
                'tahun_masuk' => $row[13],
                'no_telp' => $row[14],
                'password' => Hash::make($row[15]),
            ];
        }
        if(!empty($arr)){
            User::insert($arr)->roles()->attach(Role::where('name', 'Student'));
        }    
    if($import) {
        //redirect
        return redirect()->back()->with(['success' => 'Data Berhasil Diimport!']);
    } else {
        //redirect
        return redirect()->back()->with(['error' => 'Data Gagal Diimport!']);
    }
    }

我检查了数据库,果然,从 excel 导入数据是成功的......只是这段代码->roles()->attach(Role::where('name', 'Student'));似乎只在它不是多个数组数据时才有效(只在创建中工作,而不是插入)。

有没有办法为所有插入的数组数据批量附加关系?

标签: phparrayslaravelimportrelationship

解决方案


有没有办法为所有插入的数组数据批量附加关系?

可悲的是没有。您必须实现自定义逻辑才能将角色附加到您插入的用户。例如,您可以is_importing在当前导入的用户上添加一个布尔列。

首先将该is_importing列添加到您的用户表中,然后:

public function import_student(Request $request) 
    {
    $this->validate($request, [
        'file' => 'required|mimes:csv,xls,xlsx'
    ]);
    $import = Excel::toArray(new UserImport(), $request->file('file'));
        foreach($import[0] as $row) {
            //  dd($row[1].' '.$row[2]);
            $arr[] = [
                // If uncomment this id from here, remove [0] from foreach
                // 'id' => $row[0], 
                'nisn' => $row[1],
                'name' => $row[2],
                'username' => $row[3],
                'email' => $row[4],
                'kelas' => $row[5],
                'jabatan' => $row[6],
                'tempat_lahir' => $row[7],
                'tgl_lahir' => $row[8],
                'bulan_lahir' => $row[9],
                'tahun_lahir' => $row[10],
                'jenis_kelamin' => $row[11],
                'agama' => $row[12],
                'tahun_masuk' => $row[13],
                'no_telp' => $row[14],
                'password' => Hash::make($row[15]),
                'is_importing' => true // here we set importing to true, so our "not fully imported students" are marked
            ];
        }
        if(!empty($arr)){
            User::query()->insert($arr); //good, just be careful of the size limit of $arr, you may need to chunk it

            $role = Role::query()->where('name', 'Student')->first();

            $role->users()->syncWithoutDetaching(
               User::query()->where('is_importing', true)->pluck('id')
            ); 
            // we add all of users to the $role
            // don't forget to define the users relationship in your Role model

            User::query()->update(['is_importing' => false]);
            // we conclude our import by setting is_importing to false
        }    
    if($import) {
        //redirect
        return redirect()->back()->with(['success' => 'Data Berhasil Diimport!']);
    } else {
        //redirect
        return redirect()->back()->with(['error' => 'Data Gagal Diimport!']);
    }
}

为什么你做不到User::insert($arr)->roles()->attach(Role::where('name', 'Student'));

User::insert()User::query()->insert()允许您批量插入数据的快捷方式。它很有用,因为它速度很快,但就像它一样User::query()->update(),除了插入查询之外,它不允许您执行任何其他操作。

否则,打电话...

User::query()->insert([
   'col1' => 'val1',
   'col2' => 'val2',
]);

...就像调用:

DB::statement('INSERT INTO users (col1, col2) VALUES (val1, val2)');

它会根据查询状态返回一个布尔值(如果它插入了东西),但没有别的。

所以:

User::insert($arr)->roles()->attach(Role::where('name', 'Student')); // Call to a member function roles() on boolean

// because insert() returns a boolean it's like writing

true->roles()->attach(Role::where('name', 'Student')); // Call to a member function roles() on boolean

在当前问题之后,您将在代码中遇到的另一个问题是它->roles()->attach(Role::where('name', 'Student'))不起作用,因为attach()需要一个模型实例、一个 id 或一个 id 数组。在这里,您提供了一个查询构建器 ( Role::where('name', 'Student')),您需要附加->first().


推荐阅读