Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
44 changes: 44 additions & 0 deletions tests/Concerns/ToModelTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
use Maatwebsite\Excel\Concerns\PersistRelations;
use Maatwebsite\Excel\Concerns\ToModel;
use Maatwebsite\Excel\Tests\Data\Stubs\Database\Group;
use Maatwebsite\Excel\Tests\Data\Stubs\Database\GroupedUser;
use Maatwebsite\Excel\Tests\Data\Stubs\Database\User;
use Maatwebsite\Excel\Tests\TestCase;

Expand Down Expand Up @@ -260,4 +261,47 @@ public function model(array $row)
$this->assertEquals(2, Group::count());
DB::connection()->disableQueryLog();
}

public function test_can_import_models_with_non_nullable_belongs_to_many_relations()
{
Group::query()->truncate();
GroupedUser::query()->truncate();

DB::connection()->enableQueryLog();

$import = new class implements ToModel, PersistRelations
{
use Importable;

/**
* @param array $row
* @return GroupedUser
*/
public function model(array $row): GroupedUser
{
$groupedUser = new GroupedUser([
'name' => $row[0],
'email' => $row[1],
'password' => 'secret',
]);

$groupedUser->setRelation('group', new Group(['name' => $row[0]]));

return $groupedUser;
}
};

$import->import('import-users.xlsx');

$this->assertCount(6, DB::getQueryLog());

$users = GroupedUser::all();
$users->each(function (GroupedUser $groupedUser) {
$this->assertInstanceOf(Group::class, $groupedUser->group);
});

$this->assertCount(2, $users);
$this->assertEquals(2, Group::count());
DB::connection()->disableQueryLog();
}
}
20 changes: 20 additions & 0 deletions tests/Data/Stubs/Database/GroupedUser.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
<?php

namespace Maatwebsite\Excel\Tests\Data\Stubs\Database;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;

class GroupedUser extends Model
{
protected $fillable = [
'name',
'email',
'password',
];

public function group(): BelongsTo
{
return $this->belongsTo(Group::class);
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

class CreateGroupedUsersTable extends Migration
{
/**
* Run the migrations.
*/
public function up()
{
Schema::create('grouped_users', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->string('email');
$table->string('password');
$table->unsignedInteger('group_id')->index();

$table->timestamps();
});
}

/**
* Reverse the migrations.
*/
public function down()
{
Schema::dropIfExists('grouped_users');
}
}
Loading