Laravel / Eloquent - 如何同时运行多个原始SQL语句?

时间:2017-01-06 17:49:46

标签: php laravel laravel-5 eloquent laravel-5.2

我有多个我希望通过Eloquent运行的SQL语句。他们看起来像这样:

CREATE TEMPORARY TABLE cars
    AS (SELECT cars.id, cars.ip_address
        FROM cars
            JOIN colors ON colors.ip_address = cars.ip_address);

CREATE TEMPORARY TABLE boats
    AS (SELECT ip_address, MIN(id) AS id
        FROM colors
        GROUP BY ip_address);

CREATE TEMPORARY TABLE rvs
    AS (SELECT rvs.id, rvs.ip_address
        FROM rvs
            LEFT JOIN colors ON colors.id = rvs.id
        WHERE colors.id IS NULL);

/* Do things with temp tables here */

我需要所有这些语句在一个连接会话中运行,因为它们使用的是临时表。我已尝试在第二个语句操作开始时使用DB::statement()错误,并且DB::unprepared()似乎没有运行任何操作。

有没有办法使用Eloquent运行多个原始语句?

2 个答案:

答案 0 :(得分:5)

我认为您使用unprepared声明处于正确的轨道上,但我觉得在您的方案中使用交易可能是有利的。此外,您将要使用\DB::raw()来执行您的SQL语句作为扁平字符串。当然,不要在这里放置可以由用户提供的任何内容,因为您可以绕过参数化查询而打开自己的SQL注入。

try {
    \DB::transaction(function(){
        \DB::unprepared(\DB::raw('CREATE TEMPORARY TABLE cars AS (SELECT cars.id, cars.ip_address FROM cars JOIN colors ON colors.ip_address = cars.ip_address)'));

        \DB::unprepared(\DB::raw('CREATE TEMPORARY TABLE boats AS (SELECT ip_address, MIN(id) AS id FROM colors GROUP BY ip_address)'));

        \DB::unprepared(\DB::raw('CREATE TEMPORARY TABLE rvs AS (SELECT rvs.id, rvs.ip_address FROM rvs LEFT JOIN colors ON colors.id = rvs.id WHERE colors.id IS NULL)'));
    });

    \DB::commit();
} catch (\Exception $e){ 
    \DB::rollback();
    //do something with $e->getMessage();
}

此外,这实际上是Laravel的Query Builder而不是Eloquent

答案 1 :(得分:-1)

您应该使用laravel自定义查询。有关详细信息,请参阅此laravel documentation

$query = DB::select("       
            SELECT
                            cars.id,
                            cars.ip_address,
                        FROM cars
                        JOIN colors
                        ON colors.ip_address = cars.ip_address
                        UNION
                        SELECT
                            ip_address,
                            MIN(id) AS id,
                        FROM colors
                        GROUP BY ip_address
            UNION
                        SELECT
                            rvs.id,
                            rvs.ip_address,
                        FROM rvs
            LEFT JOIN colors 
                        ON colors.id = rvs.id
                        WHERE colors.id IS NULL
               ");