如何在Laravel中使用SQL原始查询

时间:2019-02-18 11:10:54

标签: laravel-5 laravel-query-builder

SQL表:

SQL table

SELECT id,
       account_name,
       parent_id
FROM
  (SELECT id,
          account_name,
          parent_id,
          CASE
              WHEN id = 1 THEN @idlist := CONCAT(id)
              WHEN FIND_IN_SET(parent_id, @idlist) THEN @idlist := CONCAT(@idlist, ',', id)
          END AS checkId
   FROM chart_of_account
   ORDER BY id ASC) AS T
WHERE checkId IS NOT NULL

当我在MySQL中运行此查询时,它可以正常工作,并且可以完美地获取结果,但是当我在Laravel中运行时,如下所示:

$accountId = DB::select('SELECT id,account_name,parent_id FROM
                                    (SELECT id,account_name,parent_id,
                                        CASE WHEN id = '.$account_id.' THEN @idlist := CONCAT(id)
                                                 WHEN FIND_IN_SET(parent_id,@idlist) THEN @idlist := CONCAT(@idlist,', ',id)
                                            END as checkId
                                     FROM chart_of_account
                                     ORDER BY id ASC) as T
                                WHERE checkId IS NOT NULL');

出现错误。

Argument 1 passed to Illuminate\\Database\\Connection::prepareBindings() must be of the type array, string given, 

1 个答案:

答案 0 :(得分:0)

尝试一下:

$query = 'YOUR_QUERY_THE_BIG_ONE:)';
$result = DB::select($query,[]);
dd($result);

(可选)您可以在使用用户输入的任何地方使用?登录查询,以防止mySQL注入问题,然后在select函数的第二个参数数组中提供其值。一个例子是:

$inputUserEmail = $request->input('email');
$query = 'SELECT * FROM users WHERE email=?';
$result = DB::select($query,[$inputUserEmail]);
dd($result);

我希望它能给您一个想法