【发布时间】:2021-11-06 14:23:14
【问题描述】:
我终于可以将excel数据导入数据库(虽然与通常导入的代码不同),但它无法附加关系。
三个表:users(第一个表)、role_user(关系表)和roles(第二个表)
错误:在布尔值上调用成员函数角色() Screenshot of the error
UserImport.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')); 似乎只在它不是多个数组数据时才有效(只在创建中工作,而不是插入)。
有没有办法为所有插入的数组数据批量附加关系?
【问题讨论】:
标签: php arrays laravel import relationship