Hanane
Hanane

Reputation: 347

CakePHP 3 : Can't display all data when I use first() then foreach()

I'm a beginner with CakePHP 3. My question is when we use first() in a view on a query that contains a lot of records, is it possible to get the other records using foreach()? Example :

<?=$query->first()->id ?>
// some code here 
<?= foreach($query as $value) : ?>
    <?=$value->name ?>
    <?=$value->created ?>
<?php endforeach; ?>

When I do this I don't get all the records, just the first one, even if I use foreach(). But when I delete the line <?=$query->first()->id ?> I get all the records.

Upvotes: 0

Views: 454

Answers (1)

Inigo Flores
Inigo Flores

Reputation: 4469

If the query has not been executed, the line

$query->first()->id

executes the query and applies a LIMIT 1 clause.

The following should fetch all the records and return the first.

$query->all()->first()

From the Cookboox 3.x:

Upvotes: 1

Related Questions