尝试在 Laravel 原始查询中包含变量

Trying to include Variables inside a Laravel Raw Query

试图将语句放入 ::raw 查询时让自己纠结:

  $rawStatement = "DISTINCT Product";
  $product_codes = DB::table('Chemical')
          ->JOIN('ChemicalTarget', 'Chemical.ChemicalID', '=' , 'ChemicalTarget.ChemicalID')
          ->select(DB::raw(function($query) with ($rawStatement) {
                   $query->select(DB::raw($rawStatement));
                   })
          ->orderBy('Product', 'asc')
          ->groupBy('Product')
          ->lists('Product'); //<-- This is required for existing front end.

最终我会尝试将其放入该语句中:

 CONCAT(Product, ' ', CASE WHEN :stateReg != 'Y' THEN '(not :state reg)' ELSE '' END) as label
 

 array('stateReg' => $stateRegistered, 'state' => $state)

 ->orderBy('label', 'asc')
          ->groupBy('label')
          ->lists('label'); 

如果我替换

 ->select(DB::raw(function($query) with ($rawStatement) {
                   $query->select(DB::raw($rawStatement));
                   })

 ->select(DB::raw("DISTINCT Product")

当然可以..

我使用这个 作为构建我的初始过程的参考,当我添加第二个变量时遇到了障碍,但即使我将它减少到一个,我也无法获得 ->lists()上班。

参考:https://laravel.com/docs/5.2/upgrade#upgrade-5.2.0

The lists method on the Collection, query builder and Eloquent query builder objects has been renamed to pluck. The method signature remains the same.

既然有人说您会将 lists 替换为 pluck 函数(在此页面中搜索 Retrieving A List Of Column Values

如何在闭包函数中传递多个变量:您可以使用use关键字和如下选项列表.

->select(DB::raw(function($query) use ($a, $b, $c) {
    // use $a, $b, $c
 })

但在这种情况下,您可以通过直接将原始文本放入 DB::raw() 来省略此闭包。所以你的查询可以像这样使用 $stateRegistered$state 变量。

$products = DB::table('Chemical')
          ->join('ChemicalTarget', 'Chemical.ChemicalID', '=', 'ChemicalTarget.ChemicalID')
          ->select(DB::raw("CONCAT(Product, ' ', CASE WHEN '$stateRegistered' != 'Y' THEN '(not $state)' ELSE '' END) as label"))
          ->orderBy('label', 'asc')
          ->groupBy('label')
          ->pluck('label');