在Laravel中使用DB :: select和其他文件安全吗?

时间:2018-12-11 14:55:43

标签: laravel laravel-5 query-builder laravel-query-builder

查询并不总是那么简单,有时我需要创建一个纯SQL查询,查询生成器也不适合。 注释DB :: select,подготовливаютсяли переменные,которыеподставленывзапрос?

在这种情况下会进行sql注入吗?

$mastersInCity = DB::select('SELECT
        master_user.master_id,
        masters.specialization,
        category_letter_master.category_letter_id AS master_letter,
        COUNT(*) AS count_in_city

        FROM master_user

        LEFT JOIN masters ON master_user.master_id = masters.id
        LEFT JOIN category_letter_master ON category_letter_master.master_id = master_user.master_id 

        WHERE ' . $chooiseId . ' = ' . $cityId . ' GROUP 

        BY master_user.master_id, master_letter');

或者,在这种情况下,最好直接使用PDO,以便亲自自己准备请求,这可能吗?

1 个答案:

答案 0 :(得分:2)

$mastersInCity = DB::select('SELECT
    master_user.master_id,
    masters.specialization,
    category_letter_master.category_letter_id AS master_letter,
    COUNT(*) AS count_in_city

    FROM master_user

    LEFT JOIN masters ON master_user.master_id = masters.id
    LEFT JOIN category_letter_master ON category_letter_master.master_id = master_user.master_id 

    WHERE ? = ? GROUP 

    BY master_user.master_id, master_letter', [$chooiseId, $cityId]);

这等同于准备好的语句。

文档:https://laravel.com/docs/5.7/database#running-queries

编辑:我敢肯定,简单地说就能做到,这里没有什么太复杂的。像这样:

MasterUser::with(['master', 'master_letter'])->withCount()->where($chooiseId, $cityId)->get()