Reputation: 3967
I have one database for my laravel application but I need to open two connection to it in Laravel for the following reason.
I have this code:
$pdo = DB::connection()->getPdo();
$pdo->setAttribute( PDO::MYSQL_ATTR_USE_BUFFERED_QUERY, false );
$query = $pdo->query( "SOME QUERY PULLING MILLIONS OF ROWS" );
while ( $row = $query->fetch( PDO::FETCH_ASSOC ) ) {
// Some function that writes the result to file
// and updates a row in a table to keep track of the process
}
I'm using an unbuffered query as I don't have enough memory to ready the entire result set into memory, we are talking millions of rows here. But I need to keep track of how many rows have been processed so I have a function that writes back to a status table every 10K rows processed. Problem is while an unbuffered query is running you cannot write back to MYSQL until its finished.
So what I need to do is make this unbuffered query above run it a new connection but to the same database as the application is using.
So is it possible? How do I spin up a new connection in Laravel to the same database the application is already using without closing the existing connection?
Upvotes: 2
Views: 765
Reputation: 3967
In application config create a new database connection with the same database connection details as your main database and call it something different.
Then in code you can use the second connection like so:
$pdo = DB::connection('connection 2 name here')->getPdo();
This will open a new connection if it isn't already open.
Upvotes: 0