• 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Model->chunk() with Entities

#1
I was surprised to see that chunk (https://codeigniter4.github.io/CodeIgnit...ts-of-data) was returning on object of type stdClass instead of my model-defined return type (which happens to be an entity). A simple way to replicate:
PHP Code:
$myModel = new MyModel();

foreach (
$myModel->findAll(20) as $row)
    
var_dump($row);
        
$myModel->chunk(2, function ($row)
{
    
var_dump($row);
}); 

First two objects from var_dump are App\Entities\MyEntity whereas the two from chunk() are stdClass.

I traced the difference back to system/Model.php where findAll (line ~362) passes a parameter to getResult while chunk (line ~992) doesn't.
I'm glad to open a pull request but I'm not sure if this is actually the intended/desired behavior? There's no documentation on chunk except for the user guide I linked above.

EDIT - the two different functions from Model.php in case anyone is interested:

PHP Code:
public function findAll(int $limit 0int $offset 0)
    {
        
$builder $this->builder();

        if (
$this->tempUseSoftDeletes === true)
        {
            
$builder->where($this->deletedField0);
        }

        
$row $builder->limit($limit$offset)
                ->
get();

        
$row $row->getResult($this->tempReturnType);

        
$row $this->trigger('afterFind', ['data' => $row'limit' => $limit'offset' => $offset]);

        
$this->tempReturnType     $this->returnType;
        
$this->tempUseSoftDeletes $this->useSoftDeletes;

        return 
$row['data'];
    }

...

public function 
chunk($size 100, \Closure $userFunc)
    {
        
$total $this->builder()
                ->
countAllResults(false);

        
$offset 0;

        while (
$offset <= $total)
        {
            
$builder = clone($this->builder());

            
$rows $builder->get($size$offset);

            if (
$rows === false)
            {
                throw 
DataException::forEmptyDataset('chunk');
            }

            
$rows $rows->getResult();

            
$offset += $size;

            if (empty(
$rows))
            {
                continue;
            }

            foreach (
$rows as $row)
            {
                if (
$userFunc($row) === false)
                {
                    return;
                }
            }
        }
    } 
Reply

#2
Yes, would definitely accept a PR for that as the expected behavior would be to return whatever the Model is currently set to return.
Support Development  • Practical CodeIgniter 3  • Vulcan - CLI Tools for CI4
Reply

#3
On it captain

EDIT - https://github.com/codeigniter4/CodeIgniter4/pull/1793, merged
Reply

#4
Thanks!
Support Development  • Practical CodeIgniter 3  • Vulcan - CLI Tools for CI4
Reply


Digg   Delicious   Reddit   Facebook   Twitter   StumbleUpon  


Users browsing this thread:
1 Guest(s)


  Theme © 2014 iAndrew  
Powered By MyBB, © 2002-2019 MyBB Group.