[英]Laravel : Select from three tables using eloquent
我有三张桌子
我建立了这种关系
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,标题,内容
确保您的关系定义为:
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.