通过URL将几列传递给orderBy方法

时间:2018-04-29 00:31:32

标签: php laravel rest lumen

我在Lumen 5.6(Laravel微框架)中有这个代码,我希望有几个列的orderBy方法,例如,http://apisurl/books?orderBy=devices,name,restrictions,category也发送asc或desc命令。

Lumen的文档说我们可以像这样使用orderBy

$books = PartnersBooks::all()->orderBy('device', 'asc')->orderBy('restrictions', 'asc')->get();

因此,我使用foreach创建了一个函数,用不同的orderBy请求值填充数组,并试图在没有成功的情况下进行有说服力的查询。

有人能帮助我吗?

use Illuminate\Http\Request;

public function index(Request $request)
{
    $limit = $request->input('limit');

    $books = PartnersBooks::where('is_direct', '=', 1)
      ->with('direct')
      ->whereHas('direct', function ($query) {
          $query->enable()
            ->select(['id', 'book_id', 'name', 'devices', 'flow', 'restrictions', 'countries', 'targeting']);
      })
      ->orderBy('id', 'asc')
      ->paginate($limit, ['id', 'category', 'description']);

     $status = !is_null($books) ? 200 : 204;
     return response()->json($books, $status);
}

1 个答案:

答案 0 :(得分:1)

你可以这样做:

// Get order by input
$orderByInput = $request->input('orderBy');
// If it's not empty explode by ',' to get them in an array, 
// otherwise make an empty array
$orderByParams = !empty($orderByInput) 
    ? explode(',', $orderByInput)
    : [];

$query = PartnersBooks::where('is_direct', '=', 1)
    ->with('direct')
    ->whereHas('direct', function ($query) {
      $query->enable()
        ->select(['id', 'book_id', 'name', 'devices', 'flow', 'restrictions', 'countries', 'targeting']);
    });

// Foreach over the parameters and dynamically add an orderBy
// to the query for each parameter
foreach ($orderByParams as $param) {
    $query = $query->orderBy($param);
}

// End the query and get the results
$result = $query->paginate($limit);