如何在laravel中优化查询


how to optimize query in laravel?

嗨,我想最小化这个代码:

if (empty(Input::get('channelName'))) {
    $channels = Channel::orderBy('updated_at', 'desc')->paginate($perPage)->setPath('?limit=' . $perPage);
} else {
    $channels = Channel::where('name', 'like', '%' . Input::get('channelName') . '%')->orderBy('updated_at', 'desc')->paginate($perPage)->setPath('?limit=' . $perPage);
}
$channels = Channel::orderBy('updated_at', 'desc')->paginate($perPage)->setPath('?limit=' . $perPage);
    if (empty(Input::get('channelName'))) {
        $channels = $channels->get();
    } else {
        $channels = $channels->where('name', 'like', '%' . Input::get('channelName') . '%')->get();
    }

查询生成器是一个很酷的"东西",因为它允许您链接所需的方法。这提供了根据我们的需要附加查询语句的灵活性。

$channelsQuery = Channel::orderBy('updated_at', 'desc');
if (Input::has('channelName')) {
    $channelsQuery = $channelsQuery->where('name', 'like', '%' . Input::get('channelName') . '%');
}
$channels = $channelsQuery->paginate($perPage)->setPath('?limit=' . $perPage);

在if.

中也使用Input::has('channelName')而不是仅使用empty(Input::get('channelName'))