1
votes

I need to check if a country id exists on a distant relation to a product. I only need a true or false as result. I haven't figured out how to put the query. The different relations are defined in each model:

Product - belongsToMany ShippingProfile

ShippingProfile - hasMany Methods

Method - belongsTo ShippingZone

ShippingZone - belongsToMany Countries

So if I have product id 2, and country id 5, I want to find out if the country id is available in any zone within any of the methods belonging to the profile of the product. (actually it is only one profile per product but it is defined as belongsToMany with a pivot table).

I tried to get access to countries as a first step, but I can't get access to it by using this syntax:

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

I get the error: "Call to undefined method Illuminate\\Database\\Query\\Builder::methods()

(methods() is correctly defined in shippingProfiles though).

Edit2:

Using "with", I can do a "where" check on the countries, but if I provide a non existing country, it doesn't fail - it just returns the product with the properties and a zone with an empty countries array:

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

So if you can advice any other method that will return either true/false or return the zone or null, that's what I'm looking for..

1
Have you verify that the ShippingProfile mobel has the methods relation function?Christos Papoulas
Use optional().Tpojka
Christos: yes, it has methods() with a hasMany relation to \App\MethodGalivan

1 Answers

2
votes

Use whereHas():

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