Ad

Fetch Child And Parent - Laravel Eloquent

- 1 answer

In laravel I have the below 2 models; This is the parent

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class RestaurantClass extends Model
{
    /**
     * Get the restaurants for the restaurant class.
     */
    public function restaurants()
    {
        return $this->hasMany('App\Models\Restaurant');
    }
}

And this is the child;

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class Restaurant extends Model
{    
    /**
     * Get the restaurant class that owns the restaurant.
     */
    public function restaurantClass()
    {
        return $this->belongsTo('App\Models\RestaurantClass');
    }
}

How can I retrieve the child and it's parent and vice versa (retrieve the parent and all its children)

Any guidance appreciated.

Ad

Answer

To query relationships in Laravel, use the with($relation) method on the model class you want.

Applying this to your example would be like :

Retreive the parent with its children :

$restaurantClasses = RestaurantClass::with('restaurants')->get();

// to access "children" 
foreach($restaurantClasses as $restaurantClass) {
  $restaurantClass->restaurants;
}

Retreive the children with their parent :

$restaurants = Restaurant::with('restaurantClass')->get();

// to access "parent" models
foreach($restaurants as $restaurant) {
  $restaurant->restaurantClass;
}
Ad
source: stackoverflow.com
Ad