【问题标题】:Trying to include Variables inside a Laravel Raw Query尝试在 Laravel 原始查询中包含变量
【发布时间】:2021-01-05 01:12:12
【问题描述】:

让自己纠结于试图将语句放入 ::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")

当然可以..

我使用这个link 作为参考来构建我的初始流程,当我添加第二个变量时遇到了问题,但即使我将它减少到一个,我也无法让 ->lists() 工作。

【问题讨论】:

    标签: php sql laravel list raw


    【解决方案1】:

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

    Collection、查询构建器和 Eloquent 查询构建器对象的列表方法已重命名为 pluck。方法签名保持不变。

    话虽如此,您可以将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'); 
    

    【讨论】:

    • 我已经运行了几个测试,尝试在原始代码上提取,但失败了。 (htmlstrings 不能接受对象/数组)但它的其余部分工作。谢谢
    猜你喜欢
    • 2016-10-03
    • 2017-10-01
    • 1970-01-01
    • 1970-01-01
    • 2012-10-29
    • 1970-01-01
    • 2016-07-28
    • 2021-10-30
    • 2014-01-21
    相关资源
    最近更新 更多