如何在laravel中优化查询?

时间:2016-05-13 13:23:41

标签: php 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);
}

2 个答案:

答案 0 :(得分:0)

$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();
    }

答案 1 :(得分:0)

Query Builder是一个很酷的" 事物",因为它允许您链接所需的方法。这样可以根据我们的需要灵活地附加查询语句。

$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'))