Skip to content

Commit

Permalink
[7.x] Add the ability to makeMany (create many without saving) (#33021)
Browse files Browse the repository at this point in the history
* [7.x] Add the ability to makeMany (create many without saving)

* fix code style

* Update HasOneOrMany.php

Co-authored-by: Graham Campbell <GrahamCampbell@users.noreply.github.com>
  • Loading branch information
ahmedsayedabdelsalam and GrahamCampbell authored Jun 5, 2020
1 parent b4a7e2e commit 6dee073
Show file tree
Hide file tree
Showing 2 changed files with 38 additions and 0 deletions.
17 changes: 17 additions & 0 deletions src/Illuminate/Database/Eloquent/Relations/HasOneOrMany.php
Original file line number Diff line number Diff line change
Expand Up @@ -59,6 +59,23 @@ public function make(array $attributes = [])
});
}

/**
* Create and return an un-saved instances of the related models.
*
* @param iterable $records
* @return \Illuminate\Database\Eloquent\Collection
*/
public function makeMany($records)
{
$instances = $this->related->newCollection();

foreach ($records as $record) {
$instances->push($this->make($record));
}

return $instances;
}

/**
* Set the base constraints on the relation query.
*
Expand Down
21 changes: 21 additions & 0 deletions tests/Database/DatabaseEloquentHasManyTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,27 @@ public function testMakeMethodDoesNotSaveNewModel()
$this->assertEquals($instance, $relation->make(['name' => 'taylor']));
}

public function testMakeManyCreatesARelatedModelForEachRecord()
{
$records = [
'taylor' => ['name' => 'taylor'],
'colin' => ['name' => 'colin'],
];

$relation = $this->getRelation();
$relation->getRelated()->shouldReceive('newCollection')->once()->andReturn(new Collection);

$taylor = $this->expectNewModel($relation, ['name' => 'taylor']);
$taylor->expects($this->never())->method('save');
$colin = $this->expectNewModel($relation, ['name' => 'colin']);
$colin->expects($this->never())->method('save');

$instances = $relation->makeMany($records);
$this->assertInstanceOf(Collection::class, $instances);
$this->assertEquals($taylor, $instances[0]);
$this->assertEquals($colin, $instances[1]);
}

public function testCreateMethodProperlyCreatesNewModel()
{
$relation = $this->getRelation();
Expand Down

0 comments on commit 6dee073

Please sign in to comment.