B
B
BarneyGumble2021-05-26 15:29:15
Laravel
BarneyGumble, 2021-05-26 15:29:15

How to link 4 models in Laravel?

There are 4 interconnected tables:
- hotels ( hotels )
8Anok4bfz9X1zr.jpg
- groups of amenities in hotels ( hotels_amenity_groups )
KAxolZJfZGYnK2.jpg
- amenities in hotels ( hotels_amenities )
L21zE7GFRNnGwA.jpg
- pivot table for links between amenities and hotels ( hotels_amenity_hotel )
J2bVW0BS0eB4p2.jpg

All tables in Laravel have their own models

Now I am forming a collection of hotels So:

$hotels = Hotel::with('hotels_images')->take(20)->get();


There is no information about the facilities in a particular hotel. Ultimately, I want to get this data into this collection, so that by $hotel->amenities I could get an array with amenities in this hotel, and where there would be not just a list of amenities, but also a binding to groups, for example like this:

hotel
- name
- address
- rooms
--- room
--- room
--- room
- amenities
--- group
----- group_name
----- group_amenities
------- amenity
----- -- amenity
------- amenity

How do I bind the above models to implement this?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
Dmitry, 2021-06-09
@dlnsk

Don't you think that you are trying to invent one query to solve several completely different tasks? It is unlikely that this will have a positive effect on the speed of the application.
1. When you display a list of hotels, you probably don't need a complete list of amenities, and even grouped ... Just where are you going to display them? Maybe enough number or some important, deliberately selected amenities (free parking, for example)?
2. When you search for hotels by criteria, there will be a completely different query.
3. All these amenities are needed only when displaying one hotel. So why not make multiple requests?
$amenities = $hotel->amenities()->with('groups')->get();
and then using Collection methodsgroup them however you like.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question