File tree Expand file tree Collapse file tree 2 files changed +51
-0
lines changed
src/Illuminate/Database/Eloquent Expand file tree Collapse file tree 2 files changed +51
-0
lines changed Original file line number Diff line number Diff line change @@ -629,4 +629,30 @@ public function getQueueableConnection()
629
629
630
630
return $ connection ;
631
631
}
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
+ }
632
658
}
Original file line number Diff line number Diff line change 2
2
3
3
namespace Illuminate \Tests \Database ;
4
4
5
+ use Illuminate \Database \Eloquent \Builder ;
5
6
use Illuminate \Database \Eloquent \Collection ;
6
7
use Illuminate \Database \Eloquent \Model ;
7
8
use Illuminate \Support \Collection as BaseCollection ;
@@ -455,6 +456,30 @@ public function testEmptyCollectionStayEmptyOnFresh()
455
456
$ c = new Collection ;
456
457
$ this ->assertEquals ($ c , $ c ->fresh ());
457
458
}
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
+ }
458
483
}
459
484
460
485
class TestEloquentCollectionModel extends Model
You can’t perform that action at this time.
0 commit comments