多个条件在雄辩模型上可选择哪里关系

Jai*_*cap 5 laravel eloquent laravel-4

我有桌子 training_schedules

  • id(int,pk)
  • course_reference(varchar)
  • start_date(日期)
  • end_date(日期)
  • year_id(int,fk)

years

  • id(int,pk)
  • 值(int)

现在我想使用TrainingSchedule eloquent模型创建一个搜索查询.我想搜索course_reference(使用like)并start_date(optional)基于月份(表单上的下拉列表)和年份(可选)

可选条件意味着我将检查搜索表单上是否填写了字段的表单数据.如果不是,我将跳过这些条件.

如何使用Eloquent ORM实现这一目标?如果没有,如何以另一种方式做到这一点?

ale*_*ell 4

您可以通过多个调用创建查询。因此,类似以下内容可能会满足您的要求:

// start query off with a non-optional query
$results = TrainingSchedule::whereLike('course_reference', Input::get('course_reference'));

// only if we were sent a start date, add it to the query
if (Input::has('start_date')) {
    $results->whereStartDate(Input::get('start_date'));
}

// if we were sent a month, ensure start date's month is the same month as the one passed in
if (Input::has('month')) {
    $results->where(DB::raw('MONTH(`start_date`)'), Input::get('month'));
}

// only if we were sent a year, add it to the query
if (Input::has('year')) {
    $results->whereHas('year', function ($query) { $query->whereValue(Input::get('year')); });
}

 // get actual results from db
$results = $results->get();
Run Code Online (Sandbox Code Playgroud)