Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add find method to query builder #2630

Merged
Merged
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
5 changes: 5 additions & 0 deletions src/Query/Builder.php
Original file line number Diff line number Diff line change
Expand Up @@ -129,6 +129,11 @@ public function whereNotIn($column, $values)
return $this;
}

public function find($id, $columns = ['*'])
{
return $this->where('id', $id)->get($columns)->first();
}

public function first()
{
return $this->get()->first();
Expand Down
43 changes: 43 additions & 0 deletions tests/Query/BuilderTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
<?php

namespace Tests;

use Facades\Tests\Factories\EntryFactory;
use Statamic\Facades\Collection;
use Statamic\Facades\Entry;

class BuilderTest extends TestCase
{
use PreventSavingStacheItemsToDisk;

private function createDummyCollectionAndEntries()
{
Collection::make('posts')->save();

EntryFactory::id('1')->slug('post-1')->collection('posts')->data(['title' => 'Post 1', 'author' => 'John Doe'])->create();
$entry = EntryFactory::id('2')->slug('post-2')->collection('posts')->data(['title' => 'Post 2', 'author' => 'John Doe'])->create();
EntryFactory::id('3')->slug('post-3')->collection('posts')->data(['title' => 'Post 3', 'author' => 'John Doe'])->create();

return $entry;
}

/** @test **/
public function entry_is_found_within_all_created_entries_using_entry_facade_with_find_method()
{
$searchedEntry = $this->createDummyCollectionAndEntries();
$retrievedEntry = Entry::query()->find($searchedEntry->id());

$this->assertSame($searchedEntry, $retrievedEntry);
}

/** @test **/
public function entry_is_found_within_all_created_entries_and_select_query_columns_are_set_using_entry_facade_with_find_method_with_columns_param()
{
$searchedEntry = $this->createDummyCollectionAndEntries();
$columns = ['title'];
$retrievedEntry = Entry::query()->find($searchedEntry->id(), $columns);

$this->assertSame($searchedEntry, $retrievedEntry);
$this->assertSame($retrievedEntry->selectedQueryColumns(), $columns);
}
}