Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

Indra7667's avatar

Efficient way of mass inserting data from another table

first time posting, sorry if there's wrong formats
(also if you see this post several minutes ago from another account, sorry, that was also me, just in a private account. I thought I should use a more personal, less private account for this)

Let's say I have the table 'temp_cart_items' to temporarily store user's items-to-buy
id | user_id | product_id | store_id | amount | (timestamps)

then after the user bought the items, I need to move the data to a fixed log table 'purchase_logs'
user_id | product_id | store_id | current_price | amount | (timestamps)

I know I could just go with

$cart = tempCartItem::with('productsData')->where('user_id', Auth::user()->id)->where('store_id', $store->id)->get();
foreach($cart as $value){
	purchaseLog::insert([
		'col'=>$value->something
	]);
}

but that would mean the system will have to repeat the insert query as many times as the number of item in the cart right?

is there a way to bulk insert the data more efficiently? (Especially because I need to bring the current price of the product from a related table)

0 likes
2 replies
Tray2's avatar
Tray2
Best Answer
Level 73

The easiest would be to do a raw query. Something like this.

DB::statement('INSERT INTO table2 (SELECT col1, col2 FROM table1 WHERE some_id = ?', [$id]);
1 like
Indra7667's avatar

@Tray2 oh, right, I didn't think of using raw query
I think I could implement that, I just need to read the do and don't

Thank you for the answer

Please or to participate in this conversation.