How to bulk insert with RedBeanPhp?

You are definitely right on track. Create a new bean using $bean=R::dispense('bean'); or multiple beans as an array $beans=R::dispense('bean',5);

Then you populate the beans with data:

$bean->title='Hello World!';
//or with an array
$beans[0]->title='Hello World!';
$beans[1]->title='Hello World! Bean 1';
//etc

Then store the bean(s):

R::store($bean);
//or
R::storeAll($beans);

All the beans must be the same type if you have multiples as far as I know, so you can do something like:

$beans=array();
$beans[]=R::dispense('bean');
$beans[]=R::dispense('bean');
$beans[0]->title='Hello World!';
$beans[1]->title='Hello World!1';
R::storeAll($beans);

I could be wrong about that though. The main thing is that this is all a typical ORM, but redbean also supports regular SQL if you need to use it. Hope that helps!


Some real data behind this approach. FIRST APPROACH. foreach item found

$bean = R::dispense('bean');
$bean->title = "hello";
R::store("bean");

time taken for 5660 rows = 43s on my mac

SECOND APPROACH.

$beans=array();
$beans[]=R::dispense('bean');
$beans[]=R::dispense('bean');
$beans[0]->title='Hello World!';
$beans[1]->title='Hello World!1';
R::storeAll($beans);

For 5660 rows, 46s. The storeAll is where all the time is. So its taking ages to store these beans.

THIRD APPROACH

$beans=R::dispense('bean',5560);
    
for loop
  $bean[$i]->title = "hello world";
end for
    
R::storeAll($beans);

For 5660 rows 45s. Result. None of these approaches are any quicker. : ( RedBean Transactions didn't seem to make this any quicker either

From the creator of RedBean https://stackoverflow.com/a/18811996/445492 Bulk Insert is not supported, use pure sql.

FOURTH APPROACH

for loop
  R::exec("insert into bean(title) values (1,'hello world')");
end for

for 5660 rows 7.3s <----- WOW (please note: I am actually doing some stuff prior so all these results are -4.3 seconds.)

Tags:

Php

Orm

Redbean