【问题标题】:Laravel 4.1 WhereIn w/ Many to Many Relation and Conditionals?Laravel 4.1 多对多关系和条件在哪里?
【发布时间】:2014-04-18 21:42:00
【问题描述】:

我正在开发一个应用程序,其中一部分需要使用 AND 搜索同一模型上的多个不同字段 - 又名查找年龄 whereBetween $from$to AND 其中性别为 $gender。我迷路的地方是这个模型与类别有多对多的关系,我需要在同一个查询中按类别过滤。我试图在一个查询中执行此操作,因为它需要非常快。

这是我目前所拥有的:

    $categories = Input::get('categories');

    $query = Program::with('categories')->whereIn('category', $categories)->query();

    if ($ages = Input::get('ages')) {
        $query->whereBetween('age',array($from,$to));
    }

    if ($gender = Input::get('gender')) {
        $query->where('gender','like', $gender);
    }
    // Executes the query and fetches it's results
    $programs = $query->get();

我从许多不同的来源将其汇总在一起,我想知道这是否有效,或者它是否是最有效的方法。当然有一个表programs,一个表categories,还有一个表program_category,列有idprogram_idcategory_id

提前感谢您的帮助!

【问题讨论】:

    标签: php sql orm laravel eloquent


    【解决方案1】:

    所以,最后想通了:

    $query = Program::whereHas('categories', function($q) use ($categories)
        {
            $q->whereIn('categories.id', $categories);
        });
    

    'categories' 是我的 Program 模型上的关系函数的名称。 $categories 是我的类别 ID 数组。再次感谢您的帮助。

    【讨论】:

      【解决方案2】:

      如果您查询的正确表中有可用的字段,这将起作用,您可以这样写:

      $categories = Input::get('categories');
      $query = Program::with('categories')->whereIn('category', $categories);
      // declare $from and $to if not available in the current scope
      if ($ages = Input::get('ages')) $query->whereBetween('age', array($from,$to));
      if ($gender = Input::get('gender')) $query->where('gender', $gender);
      
      // Executes the query and fetches it's results
      $programs = $query->get();
      

      【讨论】:

      • 谢谢!我现在要试试这个......会跟进。
      • 不,这不起作用,我的错是没有充分解释。类别是它自己的模型,这个模型程序与它有多对多的关系。我正在尝试通过复选框的输入数组中的类别 ID 过滤程序。这些类别 ID 在类别模型上。所以我需要查询请求类别中的程序,然后按其他输入进行过滤。
      • 我认为这种事情是我需要做的,但我不知道我在做什么:$query = Program::whereHas('category', function($q) use ($categories) { $q->whereIn('category', $categories); });
      猜你喜欢
      • 1970-01-01
      • 2020-06-18
      • 1970-01-01
      • 1970-01-01
      • 2014-07-24
      • 1970-01-01
      • 2013-11-13
      • 2015-07-20
      • 1970-01-01
      相关资源
      最近更新 更多