Retrieving relationships of relationships using Eloquent in Laravel

前端 未结 3 994
醉梦人生
醉梦人生 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:02

    It's in the official documentation under "Eager Loading"

    Multiple relationships:

    $books = Book::with('author', 'publisher')->get();
    

    Nested relationships:

    $books = Book::with('author.contacts')->get();
    

    So for you:

    Advert::find(1)->with('Car.Model')->get();
    
    0 讨论(0)
  • 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();
    
    }
    
    0 讨论(0)
  • 2020-12-25 12:23

    First you need to create your relations,

    <?php
    
    class Advert extends Eloquent {
    
        public function car()
        {
            return $this->belongsTo('Car');
        }
    
    }
    
    class Car extends Eloquent {
    
        public function model()
        {
            return $this->belongsTo('Model');
        }
    
    }
    
    class Model extends Eloquent {
    
        public function brand()
        {
            return $this->belongsTo('Brand');
        }
    
        public function cars()
        {
            return $this->hasMany('Car');
        }
    
    }
    
    class Brand extends Eloquent {
    
        public function models()
        {
            return $this->hasMany('Model');
        }
    
    }
    

    Then you just have to access this way:

    echo Advert::find(1)->car->model->brand->name;
    

    But your table fields shoud be, because Laravel guess them that way:

    id (for all tables)
    car_id
    model_id
    brand_id
    

    Or you'll have to specify them in the relationship.

    0 讨论(0)
提交回复
热议问题