简体   繁体   中英

How can I insert multiple rows into database in Laravel?

Here is my code:

$num = 5;
$voucher = new Voucher;

for ( $i = $num; $i > 0; $i-- ) {

    $token = generateRandomString(5, ['number', 'uppercase']);

    $voucher->prefix = $request->prefix;
    $voucher->token = $token;
    $voucher->description = $request->description;
    $voucher->date_time = time();
    $voucher->save();
}

Obviously my code should insert 5 rows. But surprisingly it inserts only 1 row. What's wrong and how can I fix it?

You are always using the same instance of the object. Each time you save the same row with different data. here is how to fix.

$num = 5;

for ( $i = $num; $i > 0; $i-- ) {

    $voucher = new Voucher;

    $token = generateRandomString(5, ['number', 'uppercase']);

    $voucher->prefix = $request->prefix;
    $voucher->token = $token;
    $voucher->description = $request->description;
    $voucher->date_time = time();
    $voucher->save();
}

You should create a new voucher within the for-loop. Currently, as you said, you are inserting the same object into the database five times

You are using same instance everytime! Create new one in every for loop like:

$num = 5;

for ( $i = $num; $i > 0; $i-- ) {

    $voucher = new Voucher;

    $token = generateRandomString(5, ['number', 'uppercase']);

    $voucher->prefix = $request->prefix;
    $voucher->token = $token;
    $voucher->description = $request->description;
    $voucher->date_time = time();
    $voucher->save();
}

This is basic example create multi array and simply put in insert function.

$num = 5;
$dataArray = array();
for ( $i = $num; $i > 0; $i-- ) {

    $token = generateRandomString(5, ['number', 'uppercase']);

    $dataArray[$i]['prefix'] = $request->prefix;
    $dataArray[$i]['token'] = $token;
    $dataArray[$i]['description'] = $request->description;
    $dataArray[$i]['date_time'] = time();

}

Voucher::insert($dataArray); 

If you already have a model instance, you may use the fill method to populate it with an array of attributes:

$num = 5;
$voucher = new Voucher;

for ( $i = $num; $i > 0; $i-- ) {

    $token = generateRandomString(5, ['number', 'uppercase']);

    $payload = [];
    $payload['prefix'] = $request->prefix;
    $payload['token'] = $token;
    $payload['description'] = $request->description;
    $payload['date_time'] = time();

    $voucher->fill($payload);
}

Documentation

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM