【问题标题】:Multiple where conditions on eloquent model with optional where on relationship雄辩模型上的多个 where 条件与可选的 where on 关系
【发布时间】:2014-03-17 05:21:57
【问题描述】:

我有桌子training_schedules

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

和years

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

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

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

如何使用 Eloquent ORM 实现这一目标?如果没有,怎么换一种方式呢?

【问题讨论】:

    标签: laravel laravel-4 eloquent


    【解决方案1】:

    您可以针对多个调用创建查询。因此,以下内容可能会满足您的需求:

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

    【讨论】:

    • 是的,我想出了类似的东西。现在我遇到了月份部分的问题
    • 更新您的问题,了解月份的工作方式,我会看看是否可以提供帮助 - 现在,根据您提供的信息,我看不出您需要对月份做什么.大概与 start_date 和/或 end_date 有关,但我不确定。
    • 它在帖子上。我想使用发布的月份表单数据(下拉列表)进行过滤,因此 Jan = 1、Feb = 2 等。我如何使用这些整数值来过滤数据库上的日期列(start_date)。
    • 好的,我已经更新了我的答案以照顾这个月。试一试,因为它可能并不完美,但肯定能让你继续前进。尽管您的原始问题看起来不是可选的,但我已将其视为可选输入。
    • tnx 用于更新。这会起作用,但它不可索引在这里检查我的问题stackoverflow.com/questions/22470657/…
    猜你喜欢
    • 2015-02-07
    • 1970-01-01
    • 2018-12-09
    • 2021-05-29
    • 2015-05-17
    • 2018-09-18
    • 1970-01-01
    • 2020-09-28
    • 1970-01-01
    相关资源
    最近更新 更多