亲爱的stackoverflow同事,
我很难从laravel返回一组数据。 基本上我想要实现的是:
为每个用户返回如下对象:
{'username': name_in_the_array,'totalPrice': value,}
相反,我得到一个空结果,尽管$ data变量至少有1个值。
模型/控制器的代码和结果
public static function getOrdersUser($startDate, $endDate, $user){
$orders = Order::whereBetween('orders.created_at', [new Carbon($startDate), new Carbon($endDate)])
->select(DB::raw('COALESCE(NULLIF(order_article_configurations.special_price, 0), order_article_configurations.price) * order_article_configurations.quantity AS totalPrice, orders.user_id'))
->join('order_articles', 'orders.id', '=', 'order_articles.order_id')
->join('order_article_configurations', 'order_articles.id', '=', 'order_article_configurations.order_article_id')
->where('orders.user_id', $user)
->where(function ($query) {
$query->where('orders.is_quotation', '=', '0')
->orWhereNull('orders.is_quotation');
})
->where(function ($query) {
$query->whereNull('orders.deleted_at')
->orWhereNull('order_articles.deleted_at')
->orWhereNull('order_article_configurations.deleted_at');
})
->get('totalPrice', 'orders.user_id');
return $orders;
}
下一个控制器:
public static function getOrdersUser(Request $request = null) {
if (isset($request)) {
$startDate = $request['start_date'];
$endDate = $request['end_date'];
} else {
$startDate = Carbon::now()->subDays(30);
$endDate = Carbon::now();
}
$users = ['merijn', 'stefan'];
$data = null;
$data = collect($data);
$sum = 0;
foreach($users as $user) {
$userID = collect(DB::select("SELECT id FROM users WHERE username = '$user'"))->first();
$userID = $userID->id;
$data->username = $user;
$value = Dashboard::getOrdersUser($startDate, $endDate, $userID);
foreach ($value as $x) {
$sum += $x->totalPrice;
}
$data->price = $sum;
}
return $data;
}
如果我在dd()
上使用$data
,则结果为:
Psy Shell v0.8.2 (PHP 7.1.7 — cli) by Justin Hileman
New version is available (current: v0.8.2, latest: v0.8.17)
>>> $x = App\Http\Controllers\DashboardController::getOrdersUser();
Illuminate\Support\Collection {#895
#items: []
+"username": "stefan"
+"price": 258090.16
}
但return $data
返回[]。
我希望得到的预期结果:
{ 'username':username,
'price': total value }
{ 'username': next_username,
'price': users total value
我感谢您的所有投入。 谢谢