Caius Caius - 4 months ago 57
PHP Question

How to go deeper with Eloquent hasMany in Laravel 5.2?

I'm trying to get a sort of results collection out from the db, still taking advantage of Eloquent.

I have a table called as_inspections, a table called as_green_areas and a table called as_assets

Each Inspection has a single green area, and each green area has many assets.

When I fetch the inspections I do something like this:

Inspection model



namespace App;

use Illuminate\Database\Eloquent\Model;

class Inspection extends Model
{
protected $table = 'as_inspections';

public function greenAreas()
{
return $this->hasOne('App\GreenArea', 'id');
}
}


GreenArea model



namespace App;

use Illuminate\Database\Eloquent\Model;

class GreenArea extends Model
{
protected $table = 'as_green_areas';
}


Routes



Route::get('inspections', ['middleware' => 'cors', function()
{
$isp = new \App\Inspection();
return $isp
->with('greenAreas')
->get();
}]);


Now I'd like to do something like this:

Route::get('inspections', ['middleware' => 'cors', function()
{
$isp = new \App\Inspection();
return $isp
->with('greenAreas')
->with('assets') // where each green area has its own set of assets
->get();
}]);


As written in the comment, I'd like to get all the assets for that green area, and then all the green areas for that inspection.

How can I do this?
Thanks!

Answer

Firs of all your model class and relationship will be defined like this, make sure to replace the foreign keys in the relationship function with correct one in your table,

namespace App;    //model class for inspection

use Illuminate\Database\Eloquent\Model;

class Inspection extends Model
{
    protected $table = 'as_inspections';

    public function greenArea()
    {
        return $this->belongsTo('App\GreenArea', 'greenareaid','id');
    }
}


namespace App;   //model for green area

use Illuminate\Database\Eloquent\Model;

class GreenArea extends Model
{
    protected $table = 'as_green_areas';

    public function inspection()
    {
        return $this->hasOne('App\Inspection', 'greenareaid','id');
    }

     public function assets()
    {
        return $this->hasMany('App\Asset', 'greenareaid','id');
    }
}

namespace App;   //model for asset

use Illuminate\Database\Eloquent\Model;

class Asset extends Model
{
    protected $table = 'as_assets';
     public function greenArea()
    {
        return $this->belongsTo('App\GreenArea', 'greenareaid','id');
    }

}

then you can use eager loading of eloquent to easily bring the related models as in the example bellow.. you pass the primary key of the inspection model to find method, and then grab green area and related asset for it

Inspection:find(1)->with('greenArea.assets');