Skip to content

Commit 7852011

Browse files
committed
Merge branch 'ahmedsayedabdelsalam/7.x' into 7.x
2 parents 731b94f + 15586fa commit 7852011

File tree

2 files changed

+51
-0
lines changed

2 files changed

+51
-0
lines changed

src/Illuminate/Database/Eloquent/Collection.php

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -629,4 +629,30 @@ public function getQueueableConnection()
629629

630630
return $connection;
631631
}
632+
633+
/**
634+
* Get the Eloquent query builder from the collection.
635+
*
636+
* @return Illuminate\Database\Eloquen\Builder
637+
*
638+
* @throws \LogicException
639+
*/
640+
public function toQuery()
641+
{
642+
$model = $this->first();
643+
644+
if (! $model) {
645+
throw new LogicException('Unable to create query for empty collection.');
646+
}
647+
648+
$class = get_class($model);
649+
650+
if ($this->filter(function ($model) use ($class) {
651+
return ! $model instanceof $class;
652+
})->isNotEmpty()) {
653+
throw new LogicException('Unable to create query for collection with mixed types.');
654+
}
655+
656+
return $model->newModelQuery()->whereKey($this->modelKeys());
657+
}
632658
}

tests/Database/DatabaseEloquentCollectionTest.php

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22

33
namespace Illuminate\Tests\Database;
44

5+
use Illuminate\Database\Eloquent\Builder;
56
use Illuminate\Database\Eloquent\Collection;
67
use Illuminate\Database\Eloquent\Model;
78
use Illuminate\Support\Collection as BaseCollection;
@@ -455,6 +456,30 @@ public function testEmptyCollectionStayEmptyOnFresh()
455456
$c = new Collection;
456457
$this->assertEquals($c, $c->fresh());
457458
}
459+
460+
public function testCanConvertCollectionOfModelsToEloquentQueryBuilder()
461+
{
462+
$one = m::mock(Model::class);
463+
$one->shouldReceive('getKey')->andReturn(1);
464+
465+
$two = m::mock(Model::class);
466+
$two->shouldReceive('getKey')->andReturn(2);
467+
468+
$c = new Collection([$one, $two]);
469+
470+
$mocBuilder = m::mock(Builder::class);
471+
$one->shouldReceive('newModelQuery')->once()->andReturn($mocBuilder);
472+
$mocBuilder->shouldReceive('whereKey')->once()->with($c->modelKeys())->andReturn($mocBuilder);
473+
$this->assertInstanceOf(Builder::class, $c->toQuery());
474+
}
475+
476+
public function testConvertingEmptyCollectionToQueryThrowsException()
477+
{
478+
$this->expectException(LogicException::class);
479+
480+
$c = new Collection;
481+
$c->toQuery();
482+
}
458483
}
459484

460485
class TestEloquentCollectionModel extends Model

0 commit comments

Comments
 (0)