PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Monday, February 21, 2022

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

 February 21, 2022     cakephp, cakephp-3.0, orm     No comments   

Issue

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.


Solution

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:

  • Getting the First Result
  • Getting the First & Last Record From a ResultSet


Answered By - Inigo Flores
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing