【问题标题】:How to get last relation in a nested relationship in Laravel 9.x如何在 Laravel 9.x 中获取嵌套关系中的最后一个关系
【发布时间】:2022-11-23 18:21:11
【问题描述】:

ServiceCategory有很多Service

public function services(): HasMany {
    return $this->hasMany(Service::class, 'category_id');
}

Service有很多Price

public function prices(): HasMany {
    return $this->hasMany(ServicePrice::class, 'service_id');
}

假设 prices 表有一个 price_value 列,我如何获得最低价和最高价?

我使用了this method,但每次查询都会返回ServiceCategory的列表而不是Price的列表。

我尝试了什么:

ServiceCategory::with('services.prices')->get();
// Or Even
ServiceCategory::first()->with('services.prices')->get();

和:

ServiceCategory::has('services')->with('services:category_id')->with(['services.prices' => function ($q) {
    $q->select('price');
}])->get();

仍然没有机会只返回Price的集合

【问题讨论】:

    标签: php laravel eloquent relationship


    【解决方案1】:

    最后,在尝试了所有可以让我使用的方法之后,我找到了这个解决方案(可能很乱但有效):

    ServiceCategory::has('services')
        ->getRelation('services')
        ->getRelation('prices')
        ->get();
    

    但是如果这种方法在性能方面不是最优的,请告诉我。

    【讨论】:

      猜你喜欢
      • 2021-09-07
      • 1970-01-01
      • 2020-09-13
      • 1970-01-01
      • 2020-04-14
      • 2016-09-26
      • 1970-01-01
      • 1970-01-01
      • 2020-04-04
      相关资源
      最近更新 更多