Retrieving relationships of relationships using Eloquent in Laravel

前端 未结 3 1020
醉梦人生
醉梦人生 2020-12-25 11:18

I have a database with the following tables and relationships:

Advert 1-1 Car m-1 Model m-1 Brand

If I want to retriev

3条回答
  •  悲哀的现实
    2020-12-25 12:04

    Suppose you have 3 models region,city,hotels and to get all hotels with city and region then

    Define relationship in them as follows:-

    Hotel.php

    class Hotel extends Model {
    
      public function cities(){
            return $this->hasMany(City::class);
      }
    
      public function city(){
            return $this->belongsTo('App\City','city_id');
      }
    }
    

    City.php

    class City extends Model {
    
      public function hotels(){
          return $this->hasMany(Hotel::class);
      }
    
      public function regions(){
          return $this->belongsTo('App\Region','region_id');    
      }
    }
    

    Region.php

    class Region extends Model
    {
    
      public function cities(){
          return $this->hasMany('App\City');    
      }
    
      public function country(){
          return $this->belongsTo('App\Country','country_id');
      } 
    }
    

    HotelController.php

    public function getAllHotels(){
        // get all hotes with city and region
        $hotels = Hotel::with('city.regions')->get()->toArray();
    
    }
    

提交回复
热议问题