Laravel:使用雄辩的三个表格中选择

时间:2016-11-10 12:44:55

标签: php mysql laravel eloquent

我有三张桌子

  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)
  4. 和我建立了这种关系

    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');
        }
    

    我需要从三个表中获取葡萄数据才能使用它们。

    这是我的控制器

    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');
            }
        }
    

    现在我收到错误

      

    未找到专栏

    我需要获取cat_name,sub_cat_name,title,content

1 个答案:

答案 0 :(得分:0)

确保您的关系定义为:

<强> 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');
}

您的控制器

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');
    }
}

然后在您的视图中,您可以这样做:

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