将Laravel Raw查询与占位符一起使用 [英] Using Laravel Raw Query with Placeholder

查看:559
本文介绍了将Laravel Raw查询与占位符一起使用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的模型中有以下查询:

I have this query in my Model:

型号:

 class Webmasters {
      public static function webmasters($filt, $cat) {
         $top_pages = DB::table('web.tools')
                ->where('filter',$filt)
                ->where('category', $cat)
                ->limit(20)->get();
         return $top_pages;
}

变量 $ filt $ cat 作为参数从控制器传递.

The variables $filt and $cat are passed on as parameters from the controller.

我想使用这样的查询:

 class Webmaster {
      public static function webmasters($filt, $cat) {
         $top_pages = DB::select(DB::raw("SELECT *
                                         FROM web.tools
                                         WHERE filter = $filt
                                         WHERE category = $cat
                                         LIMIT 20"));
          return $top_pages;
       }
 }

但是,我现在不在第二个查询中如何使用这些占位符.第一个工作就像一个超级按钮,但是第二个由于占位符 $ filt 给了我一个SQL错误. 和 $ cat

I however do not now how to use these placeholders on the second query. The first one works like a charm, but the second one gives me an sql error because of the placeholders $filt and $cat

推荐答案

您可以传递参数数组以绑定到选择项.

You can pass an array of parameters to bind to the select.

 class Webmaster {
      public static function webmasters($filt, $cat) {
         $top_pages = DB::select(DB::raw("SELECT *
                                         FROM web.tools
                                         WHERE filter = :filter
                                         AND category = :category
                                         LIMIT 20"), [
                                             ':filter' => $filt,
                                             ':category' => $cat
                                         ]);
          return $top_pages;
       }
 }

这篇关于将Laravel Raw查询与占位符一起使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆