【问题标题】:Create function with query in model, Laravel在模型中使用查询创建函数,Laravel
【发布时间】:2020-08-26 14:42:12
【问题描述】:

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

控制器

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;
}

【问题讨论】:

  • 还有另一种选择是制作辅助函数并将该代码放在那里,这样您就可以在项目中的任何地方使用。
  • 好的,但这也应该适用于模型,但如果我 dd($query->get()),在模型函数的开头,我没有 bestMatch 和关系从加入..
  • 试试$query = $query->count_filter($query, $request);
  • 同样的结果。我没有从加入中获得价值..
  • @Beusebiu $query = Helper::count_filter($query, $request); 并在帮助文件上创建静态函数。然后像这样打电话。

标签: laravel eloquent laravel-7


【解决方案1】:

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-04-20
    • 2017-07-30
    • 2016-06-21
    相关资源
    最近更新 更多