Laravel 5.4:在Model中编写SQL查询

时间:2017-07-23 00:52:10

标签: sql laravel model-view-controller laravel-5 laravel-query-builder

我正在开发一个小型的laravel项目,我用它在控制器中编写所有的sql查询,然后将数据发送到视图。

这是我的控制器的一个功能:

 public function view_all_applicants($job_id,$job_title)
    {

        $sql = DB::select("SELECT jm.`jobseeker_id`,jm.`jobseeker_name`,jm.`jobseeker_phone`,jm.`login_email`,jm.`jobseeker_coverletter`,jm.`jobseeker_cv`,
                  jm.`jobseeker_education`,jm.`jobseeker_experience`,jm.`jobseeker_linkedin`,aj.`cover_letter`,aj.`date_applied`
                  FROM `jobseeker_main` AS jm
                  JOIN `applicants_for_job` AS aj ON jm.`jobseeker_id`=aj.`jobseeker_id`
                  JOIN `job_details` AS jd ON jm.`jobseeker_id`=jd.`job_id`
                  WHERE aj.`job_id`=$job_id");

        $count = DB::select("SELECT COUNT(DISTINCT(aj.`afj_id`)) AS total FROM `jobseeker_main` AS jm
                             JOIN `applicants_for_job` AS aj ON jm.`jobseeker_id`=aj.`jobseeker_id`
                             JOIN `job_details` AS jd ON jm.`jobseeker_id`=jd.`job_id` WHERE aj.`job_id`=$job_id");

        foreach($count as $ss)
        {
            $data['total'] = $ss->total;
        }

        return view('company.applicants_for_job',$data,compact('sql'));     

    }

如您所见,我在这里运行两个SQL查询,然后将数据发送到视图。我的问题是,无论如何,我可以在模型(而不是控制器)中编写查询,然后将结果发送到视图?我是Laravel的新手。请帮助。

1 个答案:

答案 0 :(得分:2)

当然,您可以将上述代码完全放在相关模型中的方法中,并调用该方法。但是,通常不会直接从View中调用Model方法。 Controller应该组装View所需的数据,因此,Controller应该从Model中提取数据,然后将其传递给View。

例如:

MyModel.php

class MyModel {


    public function getX($job_id) {
       $sql = DB::select("SELECT jm.`jobseeker_id`,jm.`jobseeker_name`,jm.`jobseeker_phone`,jm.`login_email`,jm.`jobseeker_coverletter`,jm.`jobseeker_cv`,
                  jm.`jobseeker_education`,jm.`jobseeker_experience`,jm.`jobseeker_linkedin`,aj.`cover_letter`,aj.`date_applied`
                  FROM `jobseeker_main` AS jm
                  JOIN `applicants_for_job` AS aj ON jm.`jobseeker_id`=aj.`jobseeker_id`
                  JOIN `job_details` AS jd ON jm.`jobseeker_id`=jd.`job_id`
                  WHERE aj.`job_id`=$job_id");

        return $sql;
    }

    public function getCount() {
       $count = DB::select("SELECT COUNT(DISTINCT(aj.`afj_id`)) AS total FROM `jobseeker_main` AS jm
                             JOIN `applicants_for_job` AS aj ON jm.`jobseeker_id`=aj.`jobseeker_id`
                             JOIN `job_details` AS jd ON jm.`jobseeker_id`=jd.`job_id` WHERE aj.`job_id`=$job_id");

        return $count;
    }
}

Controller.php这样

public function __construct(MyModel $model)
{
   $this->model = $model;
}

public function index(Request $request, $job_id) {

   $x = $this->model->getX($job_id);
   $count = $this->model->count();

   $data['x'] = $x;
   $data['count'] = $count;

   return view('company.applicants_for_job',$data);

}

更新:

根据评论查看以上内容。