【问题标题】:Having trouble understanding how to extract the data out of the result from a query无法理解如何从查询结果中提取数据
【发布时间】:2020-03-29 16:20:47
【问题描述】:

我是 Laravel/Eloquent 的新手,我无法理解如何从查询结果中提取数据。

在 Laravel 中,我在控制器中调用以下查询

$purchase['purchase_price_total_LY'] = DB::table('coins')
        ->select(DB::raw('SUM (purchase_price) as purchase_price_total_LY'))
        ->where('user_email', '=', auth()->user()->email)
        ->whereBetween(DB::raw('DATE(purchase_date)'), [$range_lastyr_start, $range_lastyr_end])
        ->get();

并将结果传递回返回中的视图,如下所示:

return view ('pages.financials', compact('user', 'purchase'));

在视图中:

<td>Purchase Price:</td><td><a> {{$purchase['purchase_price_total_LY']}}</a></td>

视图中的结果是这样的:

[{"purchase_price_total_ly":"37"}]

当我做 dd($purchase, $purchase['purchase_price_total_LY']);我看到以下内容:

array:1 [▼
  "purchase_price_total_LY" => Illuminate\Support\Collection {#548 ▼
    #items: array:1 [▼
      0 => {#547 ▼
        +"purchase_price_total_ly": "37"
      }
    ]
  }
]
Illuminate\Support\Collection {#548 ▼
  #items: array:1 [▼
    0 => {#547 ▼
      +"purchase_price_total_ly": "37"
    }
  ]
}

从视图中的数组中提取 37 最合适的方法是什么?

【问题讨论】:

    标签: php arrays laravel eloquent


    【解决方案1】:

    如果只打算从数据库返回 1 个值,您可以像这样将 get 更改为第一个

    $purchase['purchase_price_total_LY'] = optional(DB::table('coins')
            ->select(DB::raw('SUM (purchase_price) as purchase_price_total_LY'))
            ->where('user_email', '=', auth()->user()->email)
            ->whereBetween(DB::raw('DATE(purchase_date)'), [$range_lastyr_start, $range_lastyr_end])
            ->first())->purchase_price_total_LY;
    

    【讨论】:

      【解决方案2】:

      是的,这行得通。

      我也尝试了以下方法,效果也很好。我将控制器查询更改为使用“->first()”并更改变量

      $purchase_price_total_LY = DB::table('coins')
                  ->select(DB::raw('SUM (purchase_price) as purchase_price_total_LY'))
                  ->where('user_email', '=', auth()->user()->email)
                  ->whereBetween(DB::raw('DATE(purchase_date)'), [$range_lastyr_start, $range_lastyr_end])
                  ->first();
      

      然后将返回改为:

      return view ('pages.financials', compact('user', 'purchase_price_total_LY')
      

      然后在视图中我改成这样:

      <tr><td>Purchase Price:</td><td><a>{{$purchase_price_total_LY->purchase_price_total_ly }}</a></td>
      

      现在我的答案是 37。

      【讨论】:

        猜你喜欢
        • 2011-04-05
        • 1970-01-01
        • 1970-01-01
        • 2017-04-25
        • 2020-08-06
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-07-23
        相关资源
        最近更新 更多