在模型中使用查询创建函数,Laravel

Create function with query in model, Laravel

我的控制器中有一个工作函数,但我想在模型中放置一部分代码,它是可重复的,我想在多个控制器中使用它。但是 我当前的代码不工作(没有错误)。

控制器

public function index(Request $request)
{
   $query = new Question;
   $query->select(
       ['questions.id', 
       'questions.free_text', 
       'questions.title', 
       'questions.created_at',
       'lkp_answers.name as bestMatch',
       ]);
   $query->with(['answer_history']);
   $query->join('lkp_answers', 'lkp_answers.id', '=', 'questions.best_match');
   $query->count_filter($query, $request); //here I try to use it
   return response()->json($query->paginate($request->per_page));
}

型号

public function count_filter($query, $request){
    if($request->sort_by){
        $direction = ($request->sort_direction === 'false') ? 'asc' : 'desc';

        if($request->sort_by === 'best_match'){
            $query->orderBy('lkp_answers.name', $direction);
        }else if ($request->sort_by === 'noneOfTheAbove') {
            $query->withCount(['answer_history AS none' => function ($q) {
                $q->where('answer_type', 'none');

                return $q;
            }])->orderBy('none', $direction);
        } else if ($request->sort_by === 'skipped') {
            $query->withCount(['answer_history AS skipped' => function ($q) {
                $q->where('answer_type', 'skipped');

                return $q;
            }])->orderBy('skipped', $direction);
        }  else if ($request->sort_by === 'totalVotes') {
            $query->withCount(['answer_history AS totalVotes' => function ($q) {
                $q->where('answer_type', '!=','skipped');

                return $q;
            }])->orderBy('totalVotes', $direction);
        } 
        else {
            $query->orderBy($request->sort_by,$direction);
        }
    }
    return $query;
}

问题是您为模型定义了方法,但您尝试在 eloquent 查询中调用它。您需要做的是使用另一个变量进行查询:

public function index(Request $request, Question $question)
{
   $query = $question->newQuery();
   $query->select(
       ['questions.id', 
       'questions.free_text', 
       'questions.title', 
       'questions.created_at',
       'lkp_answers.name as bestMatch',
       ]);
   $query->with(['answer_history']);
   $query->join('lkp_answers', 'lkp_answers.id', '=', 'questions.best_match');

   $question->count_filter($query, $request)

   return response()->json($query->paginate($request->per_page));
}