Skip to content

Add keyBy() to key the documents by the given key#69

Open
thekid wants to merge 2 commits into
masterfrom
feature/key-by
Open

Add keyBy() to key the documents by the given key#69
thekid wants to merge 2 commits into
masterfrom
feature/key-by

Conversation

@thekid

@thekid thekid commented Jul 13, 2026

Copy link
Copy Markdown
Member

This method keys the cursor's documents by the given key, yielding the key / value pairs.

Comparison

Before:

$claims= [];
foreach ($this->claims->find(['user' => $user]) as $claim) {
  $claims[$claim['tenant']]= $claim;
}

After:

$claims= [...$this->claims->find(['user' => $user])->keyBy('tenant')];

Overloads

  • keyBy('tenant') - uses the tenant field as keys and the docunents as associated values
  • keyBy(['tenant' => 'tokens.access']) will use the tenant field as keys and the access key in the tokens object as values
  • keyBy(fn($c) => [$c->get('tenant') => $c]) - same as above but shows the full flexibility
  • keyBy(function($c) { yield $c->get('tenant') => $c; }) - also works with generators

Prior art

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant