Tuesday, June 11, 2019

laravel Chunk without "id" column in Sqlite database

When you have to retrieve large data from a database table and want to process through it , In Laravel using Eloquent ORM or Query Builder, (Query Builder is preferred in this case for performance reasons), there is a very nice method called "Chunk" , this method requires primary key  column to be exist on the table .
From Laravel Documentation :
If you need to work with thousands of database records, consider using the chunk method. This method retrieves a small chunk of the results at a time and feeds each chunk into a Closure for processing

So, if you have a table without and Id column in it, then you cannot use this method unless you have it with another name ,if so, then you have to add this as a variable in the eloquent model :

protected $primaryKey = "theIdColumnaName";

In Sqlite databases, fortunately any table has its own id column without creating it Called "rowid" , what you need to do is to assure you have added the right property "primaryKey" to the model as given below:

protected $primaryKey = "rowid";

Then you can enjoy chunking :)

 $capsule->getConnection('sqlite')->table('users')->orderBy('rowid')->chunk(100, function ($users) {
    foreach ($users as $user) {
         echo $user->name;
        
    }
  });

No comments:

Post a Comment