Php 如何在laravel中优化查询?
嗨,我想最小化此代码:Php 如何在laravel中优化查询?,php,laravel,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
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);
}
这是一个很酷的“东西”,因为它允许你链接你需要的方法。这就提供了根据需要附加查询语句的灵活性
$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'))
$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);