Showing posts with label Eloquent. Show all posts
Showing posts with label Eloquent. Show all posts

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;
        
    }
  });

Saturday, August 17, 2013

SQLSTATE[42S02]: Base table or view not found: 1146 Table - Laravel Eloquent

If you got this error and you know for sure  that you are having the table name in your  database, Then the problem is the prefix of the table, why is that ?
I have my model declared like this :

class tableName extends Eloquent{} 

Now eloquent will take in account that table name in the database is table_names , As you see, it will add underscore before the capital letter and "s" for plural .this will happen by default unless you explicitly declare the name of the table inside the model class like this:

class tableName extends Eloquent{

protected $table = 'tableName'; 


}

Or Avoid the Capital letter in the name of the model.