Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to bulk insert with RedBeanPhp?

Tags:

php

orm

redbean

I was hoping for an example on how to bulk insert new "beans" in readbeanphp without looping over each instance.

It shows an example creating and saving a beans here: http://redbeanphp.com/manual/create_a_bean

It makes mention of storeAll($beans) method, but I am unsure exactly how I am suppose to format the data in $beans.

I have tried googling for this and can not find anything related to bulk inserts. Maybe I have searched for the wrong terms.

I am new to this ORM, any help with would appreciated, thanks!

like image 358
Chris Avatar asked Oct 08 '12 17:10

Chris


2 Answers

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!

like image 93
Tim Withers Avatar answered Nov 11 '22 04:11

Tim Withers


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.)

like image 21
John Ballinger Avatar answered Nov 11 '22 04:11

John Ballinger