laravel - Eloquent 模型上的多个 where 条件以及可选的 where on 关系

标签 laravel laravel-4 eloquent

我有表training_schedules

  • id(整数,pk)
  • 类(class)引用(varchar)
  • 开始日期(日期)
  • 结束日期(日期)
  • year_id(int,fk)

  • id(整数,pk)
  • 值(整数)

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

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

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

最佳答案

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

// 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();

关于laravel - Eloquent 模型上的多个 where 条件以及可选的 where on 关系,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22447494/

相关文章:

mysql - Eloquent ORM Laravel 关系

php - laravel 5.4 中如何匹配两个表并将其插入到另一个表中?

php - Laravel 迁移已完成,但在数据库中并不总是可见

regex - 如何检查 Laravel Blade 中的当前路线是否与模式匹配?

php - Laravel 4 旧的 mysql 凭据似乎在某处兑现?

laravel 重定向到新选项卡

php - Laravel Eloquent distinct 没有按预期工作

php - 通过某些路由前缀捕获未找到错误 [Laravel]

laravel - 如何在 Laravel 5 中过滤数据?

email - 值未定义