我有表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/