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

时间:2014-03-17 05:21:57

标签: laravel laravel-4 eloquent

我有表training_schedules

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

years

  • id(int,pk)
  • value(int)

现在我想使用TrainingSchedule eloquent模型创建搜索查询。我想根据月份(表单上的下拉列表)和年份(可选)按course_reference(使用类似)和start_date(optional)进行搜索

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

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

1 个答案:

答案 0 :(得分: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();
相关问题