Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

php - Using Laravel Raw Query with Placeholder

I have this query in my Model:

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;
}

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

I would like to use a Query like this:

 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;
       }
 }

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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;
       }
 }

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...