我正在尝试建立一个搜索引擎,但我在如何建立搜索来一片空白。我有大约5个输入字段供用户搜索(标题,usersGroup,课程,标题(问题类型))。我正在测试一个代码,它的工作只是为了根据标题搜索,但对于其他搜索它不工作,我该怎么办??
public function show_page_search()
{
$headings = heading::all();
$usersGroup = usersGroup::all();
$courses = course::all();
$questionType = $this->questionType;
return view('Admin.Page.Question.search', compact(['headings', 'usersGroup', 'courses', 'questionType']));
}
public function get_data_search(Request $request)
{
$questions = question::Where('title', 'LIKE', "%{$request->title}%")->get();
if ($request->type !== null)
$questions = $questions->where('type', $request->type)->all();这是我的模型:
class question extends Model{
protected $table = 'questions';
protected $guarded = ['id'];
public function headings()
{
return $this->belongsToMany(heading::class, 'question_headings', 'question_id', 'heading_id');
}
public function userGroup()
{
return $this->belongsToMany(usersGroup::class, 'question_users_groups', 'question_id', 'users_groups_id');
}
public function opt()
{
return $this->hasMany(questionOpt::class, 'question_id');
}
public function answer()
{
return $this->hasMany(answerQuestion::class, 'question_id');
}这是我的观点:
<tbody class="text-center">
@forelse(session()->get('questions') as $question)
<tr>
<th scope="row"><span
class="badge badge-success p-2">{{ $loop->iteration }}</span></th>
<td>
@foreach($question->headings as $heading)
<span>{{$heading->title}}, </span>
@endforeach
</td>
<td>
@foreach($question->userGroup as $userGroup)
<span>{{$userGroup->name}}, </span>
@endforeach
</td>
<td>{{get_question_type_name($question->type)}}</td>
<td>{{$question->title}}</td>
<td>发布于 2020-08-22 15:06:39
get和all以集合的形式返回结果。因此,在调用任何返回结果的方法之前,您需要构建完整的查询。
因此,请更改以下内容:
public function get_data_search(Request $request)
{
$questions = question::Where('title', 'LIKE', "%{$request->title}%")->get(); //remove this get()
if ($request->type !== null)
$questions = $questions->where('type', $request->type)->all(); //remove this all()要这样做:
public function get_data_search(Request $request)
{
$questions = Question::where('title', 'LIKE', "%{$request->title}%");
if ($request->type !== null)
$questions->where('type', $request->type); //use `like` if you want
if (another condition)
$questions->where('column', 'value');
//and finally call get() or all() or paginate() to get the final result
$questions->get();
return view('view', compact('questions'));
}https://stackoverflow.com/questions/63533406
复制相似问题