我有类别的树结构。现在,我只需要显示未在特定业务中应用的类别。
控制器中的代码
public function edit($id)
{
try
{
$id=Crypt::decrypt($id);
$business=Business::findOrFail($id);
$business_contact_details=BusinessContactDetails::where('business_id',$id)->select('contact_no','id')->get();
$business_working_hours=BusinessWorkingHours::where('business_id',$id)->get();
$business_categories=BusinessCategories::leftJoin('categories','categories.id','=','category_id')->where('business_id',$id)->where('categories.parent_id','0')->select('categories.name as name','approved','category_id','business_categories.id as id')->get();
$categories = Categories::where('parent_id', '=', 0)->get();
return view('admin.businesses.edit',compact('business','business_contact_details','business_working_hours','categories','category_counter','business_categories'));
}
catch(DecryptException $e)
{
return view('errors.404');
}
}
模型中的代码
public function subChilds(){
return $this->hasMany('App\Categories','parent_id','id')->whereNotExists(function($query){
$query->from('business_categories')->whereRaw('categories.id=business_categories.category_id')->where('business_id',2);
});
}
修改视图中的代码
<div class="col-md-6">
<ul id="tree1">
@foreach($categories as $category)
<li>
<input type="checkbox" value="{{$category->id}}" name="categories[]">
{{ $category->name }}
@if(count($category->subChilds($business->id)))
@include('admin.businesses.manageChildSub',['subChilds' => $category->subChilds($business->id)])
@endif
</li>
@endforeach
</ul>
</div>
manageChildSub视图中的代码
<ul>
@foreach($subChilds as $child)
<li>
<input type="checkbox" value="{{$child->id}}" name="categories[]">
{{ $child->name }}
@if(count($child->childs))
@include('manageChildSub',['subChilds' => $child->subChilds($business->id)])
@endif
</li>
@endforeach
</ul>
在这里,您可以看到我已经将business_id传递为2,但是我必须将其作为当前的企业ID传递。基本上,我需要使用ID调用模型函数。
更改为该类别后,我没有任何子类别。
答案 0 :(得分:3)
您可以尝试以下方法:
public function subChilds($business_id){
return $this->hasMany('App\Categories','parent_id','id')
->whereNotExists(function($query) use ($business_id){
$query->from('business_categories')
->whereRaw('categories.id=business_categories.category_id')
->where('business_id', $business_id);
});
}