在我的專案中,我有 4 個模型:
- 國家
- 城市
- 酒店
- 房間
所以.. ACountry有很多Cities,aCity有很多Hotels,等等..
現在,我想通過訪問一個 url 來顯示一個包含房間的頁面:
example.com/last-minute/{country}/{city}/{hotel}
類似的頁面example.com/last-minute/us/nyc/hilton應顯示酒店內us、酒店內nyc和酒店內的所有房間hilton。
現在我需要一個資料庫查詢來獲取我想要顯示的資料。
像這樣的作業:
$rooms = Room::where('hotel_slug', '=', $hotel)->get();
但是,當我Hilton在阿姆斯特丹等地也有酒店時,這就會產生問題。
uj5u.com熱心網友回復:
我建議您在Room模型內部創建一個區域作用域。
最好使用joins而不是whereHas(它很慢)。
<?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);
}
}
然后你可以像這樣使用它:
$rooms = Room::onPlace($country, $city, $hotel)->get();
例如
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
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/331039.html
