【问题标题】:Laravel: hasManyThrough relation to get many to many table valuesLaravel:hasManyThrough 关系获取多对多表值
【发布时间】:2019-07-07 12:45:52
【问题描述】:

我有如下three table 关系

国家 ->(有很多)省 ->(有很多)城市

我想知道 Eloquent 中是否有任何方法可以获取所有第二个孩子的国家,即城市有 status=active

我知道通过 Eloquent 提供的 hasManyThrough 关系助手可以找到单个县的活跃城市。但我需要检索all Countries who even has a single active city

注意:我不想遍历每个国家/地区。

【问题讨论】:

    标签: mysql laravel-5 eloquent


    【解决方案1】:

    使用whereHas():

    Country::whereHas('cities', function($query) {
        $query->where('status', 'active');
    })->get();
    

    【讨论】:

    • 感谢@Jonas 的回复,您能告诉我如何获得具有相同情况的单个国家/地区的省份吗?
    • 你的意思是$country->provinces()->whereHas([...])->get()
    猜你喜欢
    • 2019-08-21
    • 2021-11-25
    • 1970-01-01
    • 2020-04-29
    • 1970-01-01
    • 2023-03-25
    • 2017-05-25
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多