Yousef Altaf Yousef Altaf - 23 days ago 11
MySQL Question

Laravel : Select from three tables using eloquent

I have three tables


  1. service_cats (id - cat_name)

  2. service_sub_cats (id - cat_id - sub_cat_name)

  3. sub_cat_contents (id - sub_cat_id - title - content)



and I made this relations

serviceCat

public function serviceSubCat()
{
return $this->hasMany('ServiceSubCat');
}


serviceSubCat

public function ServicesCat()
{
return $this->belongsTo('ServiceCat', 'cat_id');
}

public function ssContent()
{
return $this->hasMany('SubCatContent');
}


subCatContent

public function ssCat()
{
return $this->belongsTo('ServiceSubCat', 'sub_cat_id');
}


I need to grape data from the three tables to use them.

here is my controller

public function show($id)
{
$serCat = ServiceCat::where('id', $id)->first();
$getId = $serCat->sub_status;
if ($getId == 1) {
$subCats = ServiceSubCat::with('ssContent')->where('cat_id', $id)->get();
//dd($subCats);
return View::make('portal.services.servicesDetailsList', compact('serCat', 'subCats'));
} else {
return View::make('portal.services.servicesDetails');
}
}


now I get Error


Column not found


I need to get the cat_name, sub_cat_name, title, content

Answer

Make sure your relations are defined as:

serviceCat

public function serviceSubCat()
{
    return $this->hasMany('ServiceSubCat', 'cat_id');
}

serviceSubCat

public function ServicesCat()
{
    return $this->belongsTo('ServiceCat', 'cat_id');
}

public function ssContent()
{
  return $this->hasMany('SubCatContent', 'sub_cat_id');
}

subCatContent

public function ssCat()
{
  return $this->belongsTo('ServiceSubCat', 'sub_cat_id');
}

your controller

public function show($id)
{
    $serCat = ServiceCat::where('id', $id)->with('serviceSubCat.ssContent')->first();
    $getId = $serCat->sub_status;
    if ($getId == 1) {
        return View::make('portal.services.servicesDetailsList', compact('serCat'));
    } else {
        return View::make('portal.services.servicesDetails');
    }
}

Then in your view you can do as:

{{ $serCat->cat_name }}
@foreach ($serCat->serviceSubCat as $ser)
    {{ $ser->sub_cat_name }}
    @foreach ($ser->ssContent as $subCatContent)
        {{ $subCatContent->title }}
        {{ $subCatContent->content }}
    @endforeach
@endforeach
Comments