Welcome Guest, Not a member yet? Register   Sign In
Model->chunk() with Entities
#1

(This post was last modified: 03-05-2019, 09:51 AM by MGatner.)

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.
Reply
#3

(This post was last modified: 03-06-2019, 10:14 AM by MGatner.)

On it captain

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

Thanks!
Reply




Theme © iAndrew 2016 - Forum software by © MyBB