Search code examples
phplaraveleloquent-relationship

How to build a query on laravel correctly?


I am grateful in advance for any answer!

there are CATEGORIES

  • CATEGORIES (one) 1⟶n PRODUCTS (many)
  • PRODUCTS (many) m⟶n STORE (one)
  • STORES (one) 1⟶n ADDRESS_CITY (many)

CATEGORIES → PRODUCTS → STORES → ADDRESS_CITY

you must select all the CATEGORIES that have:

  • there is at least 1 PRODUCT / / has
  • this PRODUCT must have a STORE in which the ADDRESS exists in California

I tried to build a query, it does not work, there is only the hasManyThrough method in the documentation
that jumps through 1 table, and there are more of them here. Or I'm even being stupid)
Help to build a query!

Another question: if I have 1 million products and 1000 stores, will the request be processed normally or do I need to look for other FEATURES:

  • save the id_city in JSON in the PRODUCTS
  • save the id_city in JSON in the STORE

Solution

  • $result = Category::where('on_off', 1)
        ->whereHas('product', function ($query) use ($city_one) {
            $query->where('on_off', 1)
    
                ->whereHas('shop', function ($query) use ($city_one) {
                    $query->where('on_off', 1)
    
                        ->whereHas('shop_map_point', function ($query) use ($city_one) {
                            $query->where('city_id', $city_one->id);
                        });
                });
        })
        ->get();