Laravel: 如何处理查询中的计数
Laravel: how to handle count in query
目前我正在控制器中获取 table list
的列表。我成功了..但是有一个问题,我 return 一个列表和一个 total.But 当有值 package
我的 count()
受限于 skip - take
。所以我必须把它分成 2 个查询。有什么办法可以将这两个查询合并为一个来压缩代码。请给我你的意见。谢谢。
public function listData(Request $request)
{
$package = $request->package;
$userId = [1,3];
$list = List::whereIn('user_id', $userId)
->when(!empty($package), function ($query) use ($package) {
$query->where('idPackage', '=' . $package);
})->orderBy('created_at', 'DESC')->skip(0)->take(20)->get()->toArray();
$count = List::whereIn('user_id', $userId)
->when(!empty($package), function ($query) use ($package) {
$query->where('idPackage', '=' . $package);
})->count();
return response()->json([
'list' => $list,
'total' => $count
], 200);
}
这很简单..我想你应该试试这个:
public function listData(Request $request)
{
$package = $request->package;
$userId = [1,3];
$list = List::whereIn('user_id', $userId)
->when(!empty($package), function ($query) use ($package) {
$query->where('idPackage', '=' . $package);
});
$count = $list->count();
$listData = $list->orderBy('created_at', 'DESC')->skip(0)->take(20)->get()->toArray();
return response()->json([
'list' => $listData,
'total' => $count
], 200);
}
祝你好运:))
目前我正在控制器中获取 table list
的列表。我成功了..但是有一个问题,我 return 一个列表和一个 total.But 当有值 package
我的 count()
受限于 skip - take
。所以我必须把它分成 2 个查询。有什么办法可以将这两个查询合并为一个来压缩代码。请给我你的意见。谢谢。
public function listData(Request $request)
{
$package = $request->package;
$userId = [1,3];
$list = List::whereIn('user_id', $userId)
->when(!empty($package), function ($query) use ($package) {
$query->where('idPackage', '=' . $package);
})->orderBy('created_at', 'DESC')->skip(0)->take(20)->get()->toArray();
$count = List::whereIn('user_id', $userId)
->when(!empty($package), function ($query) use ($package) {
$query->where('idPackage', '=' . $package);
})->count();
return response()->json([
'list' => $list,
'total' => $count
], 200);
}
这很简单..我想你应该试试这个:
public function listData(Request $request)
{
$package = $request->package;
$userId = [1,3];
$list = List::whereIn('user_id', $userId)
->when(!empty($package), function ($query) use ($package) {
$query->where('idPackage', '=' . $package);
});
$count = $list->count();
$listData = $list->orderBy('created_at', 'DESC')->skip(0)->take(20)->get()->toArray();
return response()->json([
'list' => $listData,
'total' => $count
], 200);
}
祝你好运:))