【问题标题】:Laravel HasManyThrough Relation with Where Condition on related tableLaravel HasManyThrough 与相关表上的 Where 条件的关系
【发布时间】:2021-01-17 21:43:00
【问题描述】:

我想根据医院(医生工作的地方)统计一个城市的经过验证的医生。我在 City 模式中创建了 hasManythrough 关系,当我在 blade 文件 中使用这种关系时,它会提供所有医生(已验证和未验证)。我只想找经过验证的医生。这是我的数据库结构:

数据库

医生(列) ---id--name---is_verified--

医院栏目) ---id--city_id---name---

doctor_hospitals(列) --id--hospital_id---doctor_id

城市模态中的关系

    public function cityDoctors()
    {
        return $this->hasManyThrough(
            'App\DoctorHospital',
            'App\Hospital',
            'city_id',
            'hospital_id'
        );
    }

在控制器中

 $cities=City::with('cityDoctors')->whereHas('cityDoctors')->get();

在刀片文件中我使用

   @foreach($cities as $city)
     <li><a href="{{route('typeSearch',['type' => 'city', 'id' => $city->id])}}">
        <strong>{{$city->cityDoctors->count()}}</strong>{{$city->name}}</a>
     </li>
   @endforeach

它显示所有医生的数量(已验证和未验证)。 如何只获得经过验证的城市医生?

【问题讨论】:

    标签: laravel relationship laravel-relations


    【解决方案1】:

    这就像多对多关系而不是多次抛出。

    无论如何,您可以在急切加载语句(with)中使用whereHas

      $cities = City::with(['cityDoctors' => function ($query) {
                $query->whereHas('doctor', function ($query) {
                    $query->where('is_verified', true);
                });
            }])->has('cityDoctors')->get();
    

    确保 CityDoctor 和 Doctor 模型之间的关系名称

    【讨论】:

    • 谢谢,它解决了我的问题,除了 ->has('cityDoctors') 之外,我正在尝试同样的事情。
    猜你喜欢
    • 2018-07-24
    • 2018-10-18
    • 2023-03-09
    • 2020-05-09
    • 2020-10-14
    • 1970-01-01
    • 1970-01-01
    • 2021-08-24
    • 2017-02-07
    相关资源
    最近更新 更多