Get record of first (and only) row?

11 months ago

NoNoNo
Member | 3
+
0
-

How to get the record of the first (and only) row?

// in BasePresenter:
$this->template->users = $this->DB->table('users'); // $this->DB is Nette\Database\Context
// in template:
{if count($users) == 1}
  {$users->current()->name} // Does not work
{/if}

Thanks & greetings!

11 months ago

Pavel Kravčík
Member | 995
+
0
-

$this->DB->table('users')->fetch()

Via: https://doc.nette.org/…ase-explorer#…

11 months ago

GEpic
Member | 569
+
0
-

Are you sure you want to get “first” record without any ORDER?

11 months ago

Pavel Kravčík
Member | 995
+
0
-

@GEpic: I guess he starts playing with sandbox. So he has only one user for this purpose.

11 months ago

NoNoNo
Member | 3
+
0
-

My aim is to have two different outputs in one template:

  1. Multiple users: Show list (with link to profile) e.g. /users/
  2. Single user: Show profile e.g. /users/123

In the second case (single user), this works (but is ugly) to print name of first and only user:

{foreach $users as $user}{/foreach}{$user->name}

This does not work:

{$this->DB->table('users')->fetch()->name}

Or is this approach generally wrong?

11 months ago

Ondřej Kubíček
Member | 423
+
0
-

you have to specify which user you want
you probaly want user with id 123

$this->DB->table('users')->where('id', $id)->fetch()->name

or better way

$this->DB->table('users')->get($id)->name