Laravel-在一种方法中返回多个值 [英] Laravel - Return multiple values within one method
本文介绍了Laravel-在一种方法中返回多个值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
这里是我目前停留的地方.我正在使用多种方法对同一张表进行不同的查询:
Heres where I'm currently stuck at. I am doing multiple methods where I am doing the different queries to the same table:
public function totalOfA()
{
return $a = Stocks::where('user_id','=', $this->employee->id)
->where('category','=','a')
->pluck('qty')
->sum();
}
public function totalOfB()
{
return $a = Stocks::where('user_id','=', $this->employee->id)
->where('category','=','a')
->pluck('qty')
->sum();
}
我正在尝试一种求和方法,将所有功能汇总为一个函数
I'm trying to look for a way to sum that all up to just one function
public function totalStocks()
{
$stocks = Stocks::where('user_id','=', $this->employee->id)
->get();
$a = $stocks::where('category', '=', 'a')
->pluck('qty')
->sum();
$b = $stocks::where('category', '=', 'b')
->pluck('qty')
->sum();
return $a and $b
}
所以我可以从视图中将其称为totalstocks()-> a或totalstocks()-> b之类的东西.
So I can just call it from view as totalstocks()->a or totalstocks()->b something like that.
推荐答案
您不能那样打电话.您可以创建aray或单独通过查看
You cant call like that.you can create an aray or you can pass seperately to view
public function totalStocks()
{
$stocks = Stocks::where('user_id','=', $this->employee->id)
->get();
$a = $stocks::where('category', '=', 'a')
->pluck('qty')
->sum();
$b = $stocks::where('category', '=', 'b')
->pluck('qty')
->sum();
return view('home',['stocks'=> $stocks,'a'=>$a,'b'=>$b]);
}
现在,您可以在视图中访问$ a,$ b
Now you can access $a ,$b in your view
public function totalStocks()
{
$data['stocks'] = Stocks::where('user_id','=', $this->employee->id)
->get();
$data['a'] = $stocks::where('category', '=', 'a')
->pluck('qty')
->sum();
$data['b'] = $stocks::where('category', '=', 'b')
->pluck('qty')
->sum();
return view('home',['data'=>$data]);
}
因此您可以在{{$data['a']}}
这篇关于Laravel-在一种方法中返回多个值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文