雄辩-检查ID是否存在于远距离关系中

时间:2018-10-12 12:14:51

标签: laravel eloquent

我需要检查与产品的远距离关系中是否存在国家/地区ID。结果只需要是对还是错。我还没有弄清楚如何进行查询。每个模型中定义了不同的关系:

产品-属于到很多运输资料

ShippingProfile-有很多方法

方法-属于ShippingZone

ShippingZone-属于许多国家/地区

因此,如果我有产品ID 2和国家/地区ID 5,我想确定该国家/地区ID在属于该产品资料的任何方法中的任何区域中是否可用。 (实际上,每个产品只有一个配置文件,但它定义为带有数据透视表的belongsToMany)。

第一步,我尝试访问国家/地区,但使用以下语法无法访问它:

$prod = \App\Product::find(2)
       ->shipping_profiles()
       ->methods()->zones()->countries();

我收到错误消息:“ Call to undefined method Illuminate\\Database\\Query\\Builder::methods()

(尽管methods()在shippingProfiles中已正确定义)。

Edit2

使用“ with”,我可以对国家/地区进行“ where”检查,但是如果我提供的国家/地区不存在,它不会失败-它只会返回带有属性的产品和带有空国家的区域数组:

return $prod = \App\Product::find(2)->with([
            'shipping_profiles.methods.zone.countries' => function($query) {
             $query->where('countries.id', 10000);
       }])->firstOrFail();

因此,如果您可以建议其他任何将返回true / false或返回zone或null的方法,那就是我想要的。

1 个答案:

答案 0 :(得分:1)

使用whereHas()

return $prod = \App\Product::whereKey(2)->whereHas(
    'shipping_profiles.methods.zone.countries', function($query) {
        $query->where('countries.id', 10000);
    })->firstOrFail();
相关问题