简体   繁体   中英

Having trouble understanding how to extract the data out of the result from a query

I am new to Laravel/Eloquent and I'm having trouble understanding how to extract the data out of a result from a query.

In Laravel I'm calling the following query in the controller

$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();

and passing the result back to the view in the return as follows:

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

In the view:

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

The result in the view is this:

[{"purchase_price_total_ly":"37"}]

When I do a dd($purchase, $purchase['purchase_price_total_LY']); I see the following:

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"
    }
  ]
}

What's the most appropriate way to extract the 37 out of the array in the view?

If there's only meant to be 1 value being returned from the database, you can change the get to a first like so

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

Yes, that worked.

I also attempted the following and it worked as well. I changed the controller query to use "->first()" and change the variable

$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();

then changed the return to this:

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

Then in the view I changed to this:

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

and now I have an answer of 37.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM