我尝试创建一个函数,在运行搜索后,我可以随机返回结果集中结果中指定的数字。
搜索工作正常。但我需要能够根据用户输入从结果集中进行选择(例如,用户希望从返回的结果集中获取100条记录)。
这是我的查询代码
class Business extends Model
{
protected $table = 'businesses_old';
/*
* Return search result on bussinesses
* @param $params array
* @return mixed
*/
public static function search($params){
$businesses = self::query();
if(isset($params['business']) && $params['business']!=''){
$businesses->where('name','like', "%".$params['business']."%");
/*$businesses->orWhere('contact_first_name','like', "%".$params['business']."%");
$businesses->orWhere('contact_last_name','like', "%".$params['business']."%");
$businesses->orWhere('email','like', "%".$params['business']."%");
$businesses->orWhere('address_1','like', "%".$params['business']."%");
$businesses->orWhere('address_2','like', "%".$params['business']."%");*/
$businesses->orWhere('website','like', "%".$params['business']."%");
/*$businesses->orWhere('city','like', "%".$params['business']."%");*/
$businesses->orWhere('description','like', "%".$params['business']."%");
/*$businesses->orWhere('state','like', "%".$params['business']."%");*/
}
$businesses->orderBy('name','ASC');
return $businesses->paginate(20);
}
public static function InRandom($businesses) {
$random = inRandomOrder($businesses);
}
}
以下是搜索控制器的代码
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Input;
use App\Business;
class SearchController extends Controller
{
/**
* Display search form
*
* @return mixed
*/
public function index(){
return view('search/index');
}
/**
* Display search results
*
* @return mixed
*/
public function indexHandle(){
$params=[];
if($business = Input::get('business')){
$params['business']=$business;
}
$businesses='';
if(!empty($params)){
$businesses=Business::search($params);
}else{
return redirect('/search');
}
return view('search/result', compact('businesses','business'));
}
}
答案 0 :(得分:1)
如果我理解正确,你必须改变这一行
$businesses->orderBy('name','ASC');
有了这个
$businesses->inRandomOrder();
这将从整个表中随机播放记录,然后从随机结果中获得20条记录(针对当前页面)。
<强>但是强>
分页现在不会像您期望的那样起作用,因为每次运行search
函数时,随机化结果都会有所不同。
答案 1 :(得分:0)
这应该适用于MySQL,只需更改LIMIT以满足您的需求:
ORDER BY RAND()
LIMIT 1