|
| 1 | +<?php namespace GeneaLabs\LaravelModelCaching\Tests\Integration\CachedBuilder; |
| 2 | + |
| 3 | +use GeneaLabs\LaravelModelCaching\Tests\Fixtures\Book; |
| 4 | +use GeneaLabs\LaravelModelCaching\Tests\Fixtures\Publisher; |
| 5 | +use GeneaLabs\LaravelModelCaching\Tests\Fixtures\UncachedBook; |
| 6 | +use GeneaLabs\LaravelModelCaching\Tests\Fixtures\UncachedPublisher; |
| 7 | +use GeneaLabs\LaravelModelCaching\Tests\IntegrationTestCase; |
| 8 | +use Illuminate\Database\Eloquent\Collection; |
| 9 | + |
| 10 | +class SubQueryAddSelectTest extends IntegrationTestCase |
| 11 | +{ |
| 12 | + public function testAddSelect() |
| 13 | + { |
| 14 | + $key = sha1("genealabs:laravel-model-caching:testing:{$this->testingSqlitePath}testing.sqlite:books:genealabslaravelmodelcachingtestsfixturesbook_books.*_(select \"name\" from \"publishers\" where \"id\" = \"books\".\"publisher_id\" order by \"published_at\" desc limit 1) as \"publisher_name\"-publisher_id_in_11_12_13_14_15"); |
| 15 | + $tags = [ |
| 16 | + "genealabs:laravel-model-caching:testing:{$this->testingSqlitePath}testing.sqlite:genealabslaravelmodelcachingtestsfixturesbook", |
| 17 | + ]; |
| 18 | + |
| 19 | + /** @var Collection $publishers */ |
| 20 | + $publishers = factory(UncachedPublisher::class, 5)->create(); |
| 21 | + |
| 22 | + $publishers->each(function (UncachedPublisher $publisher) { |
| 23 | + factory(UncachedBook::class, 2)->create(['publisher_id' => $publisher->id]); |
| 24 | + }); |
| 25 | + |
| 26 | + $publisherIds = $publishers->pluck('id')->toArray(); |
| 27 | + |
| 28 | + $books = Book::whereIn('publisher_id', $publisherIds) |
| 29 | + ->addSelect(['publisher_name' => |
| 30 | + Publisher::select('name') |
| 31 | + ->whereColumn('id', 'books.publisher_id') |
| 32 | + ->orderBy('published_at', 'desc') |
| 33 | + ->limit(1) |
| 34 | + ])->get()->pluck('publisher_name')->filter()->toArray(); |
| 35 | + |
| 36 | + $cachedResults = $this |
| 37 | + ->cache() |
| 38 | + ->tags($tags) |
| 39 | + ->get($key)['value']; |
| 40 | + |
| 41 | + $liveResults = UncachedBook::whereIn('publisher_id', $publisherIds) |
| 42 | + ->addSelect(['publisher_name' => |
| 43 | + UncachedPublisher::select('name') |
| 44 | + ->whereColumn('id', 'books.publisher_id') |
| 45 | + ->orderBy('published_at', 'desc') |
| 46 | + ->limit(1) |
| 47 | + ])->get()->pluck('publisher_name')->filter()->toArray(); |
| 48 | + |
| 49 | + $this->assertCount(10, $books); |
| 50 | + $this->assertSame($liveResults, $books); |
| 51 | + $this->assertSame($liveResults, $cachedResults->pluck('publisher_name')->filter()->toArray()); |
| 52 | + } |
| 53 | +} |
0 commit comments