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

Friday, February 4, 2022

[FIXED] How to append to a CakePHP3 ResultSet?

 February 04, 2022     cakephp, cakephp-3.0, iterator     No comments   

Issue

I have a query (a Query object):

$joblineitems = $this->JobLineItems->find('all');

It has results (a ResultSet object):

$joblineitemsresults = $joblineitems->all();

The ResultSet object is an Iterable such that a foreach() loop will return each of the JobLineItem objects.

I simply want to add an additional result to $joblineitemsresults - specifically I want to append a $this->JobLineItems->newEntity() to the end of the results so that when I subsequently paginate $joblineitemsresults and loop through it in the view, the last object in the loop on the last page will be a blank object with the property new=true.

How can I manually append an extra result to a ResultSet object?


Solution

try this

$joblineitems = $this->JobLineItems->find('all');
$joblineitemsresults = $joblineitems->all();

$joblineitemsresults = $joblineitemsresults ->append([$this->JobLineItems->newEntity()]);
debug($joblineitemsresults ->toList());

You can see the manual for reference

pay attention in particular to the last paragraph

When appending from different sources, you can expect some keys from both collections to be the same. For example, when appending two simple arrays. This can present a problem when converting a collection to an array using toArray(). If you do not want values from one collection to override others in the previous one based on their key, make sure that you call toList() in order to drop the keys and preserve all values.

That's why I used toList() instead of toArray(). If you use toArray() you'll see the new entity override the first one.

Of course you can also transform your recordset in an array and then append the new entity to the array

$joblineitemsresults = $joblineitems->toArray();
joblineitemsresults[] = $this->JobLineItems->newEntity();


Answered By - arilia
  • 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