【问题标题】:Laravel 5.1 How to get all models and related models by querying a related model?Laravel 5.1 如何通过查询一个相关模型得到所有模型和相关模型?
【发布时间】:2015-11-24 00:01:49
【问题描述】:

模型关系... 公寓有许多平面图。 公寓有很多照片。 Floorplan 有很多 FloorplanImage。

我想获得所有具有 0 间卧室的平面图的公寓。 另外,我想获取相关的照片和相关的 FloorplanImage。

我有点没用的代码...

    $apartmentsWithStudios = Floorplan::with(['apartment', 'floorplanImage'])
                                        ->where('bedrooms', '=', 0)->get();

如何通过查询 Floorplan 模型来获取 Apartment 和所有相关模型?有可能吗?

【问题讨论】:

    标签: eloquent laravel-5.1


    【解决方案1】:

    whereHas + with:

    Apartment::whereHas('floorplans', function ($floorplans) {
      /** @var \Illuminate\Database\Eloquent\Query */
      $floorplans->where('bedrooms', 0);
    })
    
      // with all floorplans and their images
      ->with('photo', 'floorplans.floorplanImage')
    
      // OR with floorplans without bedrooms and their images
      ->with(['phooto', 'floorplans' => function ($floorplans) {
         $floorplans->where('bedrooms', 0);
      }, 'floorplans.floorplanImage'])
    
      ->get();
    

    【讨论】:

    • 缺少结束 ] 与第二个。除此之外,代码正是我所需要的。
    猜你喜欢
    • 2016-05-04
    • 2020-05-25
    • 1970-01-01
    • 1970-01-01
    • 2017-11-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多