Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to execute a raw sql query with multiple statement with laravel

Tags:

php

mysql

laravel

Is there anyway I can execute a query with multiple statement like the one below, using laravel framework. I have tried using DB::statement but returned a sql syntax error, but when I execute the same query on phpmyadmin I works, its so frustrating. Please help me.

EG

LOCK TABLE topics WRITE;

SELECT @pRgt := rgt FROM topics WHERE id = ?;

UPDATE topics SET lft = lft + 2 WHERE rgt > @pRgt;
UPDATE topics SET rgt = rgt + 2 WHERE rgt >= @pRgt;

INSERT INTO topics (title, overview, article, image, lft, rgt)
VALUES (?, ?, ?, ?, @pRgt, @pRgt + 1);

UNLOCK TABLES;
like image 728
Eddie Dane Avatar asked May 20 '18 20:05

Eddie Dane


People also ask

How do I run multiple SQL statements in one query?

To run a query with multiple statements, ensure that each statement is separated by a semicolon; then set the DSQEC_RUN_MQ global variable to 1 and run the query. When the variable is set to zero, all statements after the first semicolon are ignored.

What is DB :: Raw in Laravel?

DB::raw() is used to make arbitrary SQL commands which aren't parsed any further by the query builder. They therefore can create a vector for attack via SQL injection.


1 Answers

DB::unprepared() should do the trick , laravel prepare and do some stuff for sql queries .
But instead you can use absolutely raw ones using DB::unprepared .

EG

DB::unprepared('LOCK TABLE topics WRITE;

SELECT @pRgt := rgt FROM topics WHERE id = ?;

UPDATE topics SET lft = lft + 2 WHERE rgt > @pRgt;
UPDATE topics SET rgt = rgt + 2 WHERE rgt >= @pRgt;

INSERT INTO topics (title, overview, article, image, lft, rgt)
VALUES (?, ?, ?, ?, @pRgt, @pRgt + 1);

UNLOCK TABLES;');

It will execute your whole SQL query whether it is single/multiple statements .

like image 138
TheSalamov Avatar answered Sep 27 '22 19:09

TheSalamov