【问题标题】:Laravel eloquent - Filtering subquery inside with statementLaravel 雄辩 - 用语句过滤子查询
【发布时间】:2019-02-20 23:09:44
【问题描述】:

我有以下查询:

 $countries = Country::where('code', '=', $code)
 ->with(array('cities.details' => function ($query) use ($user) {
 $query->where('cities.name', '=', 'This is a city name');
 }))->first();

让我们看看这个例子:我有三个表,CountryCityCityDetails。我想获取所有国家/地区,然后获取所有城市(包括详细信息),但我还希望按名称过滤城市获取属于城市表的详细信息表 e.

如果我想使用with(cities.details) 来获取子表和另一个表,如何使用 CITIES 属性进行过滤?

主要问题是:如何在 secondTable.OtherTable 这样的 with 语句中获取两个表并使用 secondTable 属性过滤查询?

只是为了更清楚,如果我使用这样的语句:

  $countries = Country::where('code', '=', $code)
 ->with(array('cities.details' => function ($query) use ($user) {
    $query->where('name', '=', 'This is a detail name');
    }))->first();

我只能访问 details 表属性。问题是:如何访问 city 表属性以在 with 语句中进行过滤?

提前致谢

【问题讨论】:

    标签: php laravel eloquent


    【解决方案1】:

    我刚刚找到了解决方案。基本上,我应该为 city 表应用过滤器,然后在子查询上调用 wit 函数。这段代码解决了我的问题:

        $countries = Country::where('code', '=', $code)
     ->with(array('cities' => function ($query) use ($user) {
        $query->where('name', '=', 'San Francisco')->with('details');
        }))->first();
    

    请注意,我仅在子查询中过滤后才在城市上调用 with('details')

    【讨论】:

      【解决方案2】:

      最直接的一种是使用连接查询:

      (new Country)
          ->join('cities', 'cities.id', '=', 'countries.city_id')
          ->join('city_details', 'cities.id', '=', 'city_details.city_id')
          ->where('cities.name', 'TheName')
          ->where('city_details.info', 'info')
          ->select('...');
      

      但结果只有一个级别。所以,

      $query = (new Models\Country())
          ->with([
              'cities' => function ($query) {
                  $query->where('name', 'xxx')->with([
                      'details' => function ($query) {
                          $query->where('info', 'info');
                      }
                  ]);
              }
          ]);
      
      $result = $query->get()->filter(function ($item) {
          return count($item['cities']);
      });
      

      结果给出了空城市的国家。所以最后使用 Laravel 集合进行过滤。

      【讨论】:

        猜你喜欢
        • 2018-11-18
        • 1970-01-01
        • 1970-01-01
        • 2013-02-02
        • 2020-03-24
        • 1970-01-01
        • 2017-11-11
        • 2018-01-26
        • 2021-07-23
        相关资源
        最近更新 更多