douyan1921 2016-10-26 07:26
浏览 78
已采纳

如何将参数传递给查询?

I use Laravel. As you know, Laravel doesn't support UNION clause for the query. So I have to write it as raw when I want to paging the whole results. Something like this:

$results = DB::select('SELECT id, title, description, imgPath
                       FROM news n
                       WHERE n.title LIKE %$q OR n.description LIKE %$q 
                       UNION ALL
                       SELECT id, title, description, imgPath
                       FROM productions p
                       WHERE p.title LIKE %$q OR p.description LIKE %$q
                      ');

As I said, I use Laravel, So how can I pass $q to the query in Laravel? All I'm trying to do is making the query safe against SQL injections. That's why I'm trying to pass the parameters to the query rather that using them directly in the query.


In pure PHP I can do that like this:

$st = $dbh->prepare('SELECT ... WHRER col LIKE %:q');
$st->bindParam(':q', $q, PDO::PARAM_INT);

I want something like this ^ in Laravel.

  • 写回答

2条回答 默认 最新

  • doubomudichen0832 2016-10-26 07:32
    关注

    Yes, there is union: https://laravel.com/docs/5.3/queries#unions

    I didn't test it out, but it should looks something like this:

    $first = DB::table('news')
        ->select(['id', 'title', 'description', 'imgPath'])
        ->where(function($query) use ($q) {
            $query->where('title', 'like', "%$q")
                  ->orWhere('description', 'like', "%$q");
        });
    
    $result = DB::table('productions')
        ->select(['id', 'title', 'description', 'imgPath'])
        ->where(function($query) use ($q) {
            $query->where('title', 'like', "%$q")
                  ->orWhere('description', 'like', "%$q");
        })
        ->unionAll($first)
        ->get();
    

    NOTE:

    With union you won't be able to do paginate out of the box. You will need to create the paginator object by yourself as shown here: Laravel - Union + Paginate at the same time?

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 TLS1.2协议通信解密
  • ¥40 图书信息管理系统程序编写
  • ¥20 Qcustomplot缩小曲线形状问题
  • ¥15 企业资源规划ERP沙盘模拟
  • ¥15 树莓派控制机械臂传输命令报错,显示摄像头不存在
  • ¥15 前端echarts坐标轴问题
  • ¥15 ad5933的I2C
  • ¥15 请问RTX4060的笔记本电脑可以训练yolov5模型吗?
  • ¥15 数学建模求思路及代码
  • ¥50 silvaco GaN HEMT有栅极场板的击穿电压仿真问题