Retrieving relationships of relationships using Eloquent in Laravel

前端 未结 3 1022
醉梦人生
醉梦人生 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条回答
  •  猫巷女王i
    2020-12-25 12:23

    First you need to create your relations,

    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.

提交回复
热议问题