Home > Enterprise >  Database query multiple parameters, multiple models
Database query multiple parameters, multiple models

Time:10-21

In my project I have 4 models:

  • Country
  • City
  • Hotel
  • Room

So.. A Country has many Cities, a City has many Hotels, and so on..

Now, I want to display a page with rooms by accessing an url like:

example.com/last-minute/{country}/{city}/{hotel}

A page like example.com/last-minute/us/nyc/hilton should display all rooms within the us, within nyc and within the hilton hotel.

Now I need a database query to get the data that I want to display.

Something like this works:

$rooms = Room::where('hotel_slug', '=', $hotel)->get();

But this creates a problem when I als have a Hilton hotel in, for example, Amsterdam.

CodePudding user response:

I suggest you to create a local scope inside Room model.

Better to use joins instead of whereHas (it's very slow).

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class Room extends Model
{
    public function scopeOnPlace($query, $country, $city, $hotel)
    {
        return $query->select('rooms.*')
            ->join('hotels', 'rooms.hotel_id', '=', 'hotels.id')
            ->join('cities', 'hotels.city_id', '=', 'cities.id')
            ->join('countries', 'cities.country_id', '=', 'countries.id')
            ->where('countries.slug', $country)
            ->where('cities.slug', $city)
            ->where('hotels.slug', $hotel);
    }
}

Then you can use it like:

$rooms = Room::onPlace($country, $city, $hotel)->get();

For example

Route::get('last-minute/{country}/{city}/{hotel}', [LastMinuteController::class, 'show']);
class LastMinuteController extends Controller
{
    public function show($country, $city, $hotel)
    {
        $rooms = Room::onPlace($country, $city, $hotel)->get();
    }
}

https://laravel.com/docs/8.x/eloquent#local-scopes

  • Related